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

前端 未结 8 527
无人共我
无人共我 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 06:50

    Good Question & Matt's was a good answer. To expand on the syntax a little if the oldtable has an identity a user could run the following:

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

    That would be if the oldtable was scripted something as such:

    CREATE TABLE [dbo].[oldtable]
    (
        [oldtableID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
        [col1] [nvarchar](50) NULL,
        [col2] [numeric](18, 0) NULL,
    )
    
    0 讨论(0)
  • 2021-02-02 06:52

    You could do a Select Into, which would create the table structure on the fly based on the fields you select, but I don't think it will create an identity field for you.

    0 讨论(0)
  • 2021-02-02 06:53

    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

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-02 07:03

    If you want to include the column that is the current identity, you can still do that but you have to explicitly list the columns and cast the current identity to an int (assuming it is one now), like so:

    select cast (CurrentID as int) as CurrentID, SomeOtherField, identity(int) as TempID 
    into #temp
    from myserver.dbo.mytable
    
    0 讨论(0)
  • 2021-02-02 07:05

    If after the *, you alias the id column that is breaking the query a secondtime... and give it a new name... it magically starts working.

    select IDENTITY( int ) as TempID, *, SectionID as Fix2IDs
    into #TempSections
    from Files_Sections
    
    0 讨论(0)
提交回复
热议问题