Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT INTO a temp table, and have an IDENTITY field created, without first declaring the temp table?

Tags:

sql

sql-server

I need to select a bunch of data into a temp table to then do some secondary calculations; To help make it work more efficiently, I would like to have an IDENTITY column on that table. I know I could declare the table first with an identity, then insert the rest of the data into it, but is there a way to do it in 1 step?

like image 902
Dale B Avatar asked Sep 23 '08 20:09

Dale B


People also ask

How do you create an identity column in a temp table?

How to have an identity column for a temp table in SQL? Explicit value must be specified for identity column in table '#T' either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column.

How will you insert values into temp table with identity column in SQL Server?

Should read Insert into #temp (MyID, MyName) as you have listed 3 fields to insert but only entered 2 fields, as you are using an identity field you need not enter a value for this. Thanks for the help. There's an alternative syntax which you may find more intuitive: SELECT IDENTITY(int, 1, 1) AS RowID, ...


2 Answers

Oh ye of little faith:

SELECT *, IDENTITY( int ) AS idcol   INTO #newtable   FROM oldtable 

http://msdn.microsoft.com/en-us/library/aa933208(SQL.80).aspx

like image 148
Matt Rogish Avatar answered Sep 24 '22 18:09

Matt Rogish


You commented: not working if oldtable has an identity column.

I think that's your answer. The #newtable gets an identity column from the oldtable automatically. Run the next statements:

create table oldtable (id int not null identity(1,1), v varchar(10) )  select * into #newtable from oldtable  use tempdb GO sp_help #newtable 

It shows you that #newtable does have the identity column.

If you don't want the identity column, try this at creation of #newtable:

select id + 1 - 1 as nid, v, IDENTITY( int ) as id into #newtable      from oldtable 
like image 36
boes Avatar answered Sep 22 '22 18:09

boes