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

前端 未结 8 531
无人共我
无人共我 2021-02-02 06:16

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

8条回答
  •  野的像风
    2021-02-02 07:03

    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
    

提交回复
热议问题