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

前端 未结 8 528
无人共我
无人共我 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:09

    To make things efficient, you need to do declare that one of the columns to be a primary key:

    ALTER TABLE #mytable
    ADD PRIMARY KEY(KeyColumn)
    

    That won't take a variable for the column name.

    Trust me, you are MUCH better off doing a: CREATE #myTable TABLE (or possibly a DECLARE TABLE @myTable) , which allows you to set IDENTITY and PRIMARY KEY directly.

    0 讨论(0)
  • 2021-02-02 07:11

    IIRC, the INSERT INTO command uses the schema of the source table to create the temp table. That's part of the reason you can't just try to create a table with an additional column. Identity columns are internally tied to a SQL Server construct called a generator.

    0 讨论(0)
提交回复
热议问题