Put multiple table data into one and add special data plus identity column - SQL Server

Say you want to combine the data from 3 tables - a1, a2, and a3.

Now, you also want to add a special field, let's say it's the year, and it's 2001 for a1 2002 for a2 etc'

In addition, you want the resluting table to have an identity column. What do you do?

 

This is a real - life scenario which came up today, and here's the solution:

select  IDENTITY(int, 1,1) AS id_num , *
into a
from
(
select  2001 as year ,* from a1
union
select  2002,* from a2
union
select  2003,* from a3
)  as t


select * from a

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
posted @ Thursday, April 12, 2007 9:11 AM
Print

Comments on this entry:

No comments posted yet.

Your comment:



(not displayed)


 
 
 
 
 

Live Comment Preview:

 
«February»
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910