T-SQL Insert into table without having to specify every column

后端 未结 7 2521
悲&欢浪女
悲&欢浪女 2021-02-18 13:25

In our db there is a table that has a little over 80 columns. It has a primary key and Identity insert is turned on. I\'m looking for a way to insert into this table every colum

7条回答
  •  难免孤独
    2021-02-18 14:05

    No, that's not possible. You could be tempted to use

    INSERT INTO MyLargeTable SELECT * FROM OtherTable
    

    But that would not work, because your identity column would be included in the *.

    You could use

    SET IDENTITY_INSERT MyLargeTable ON
    INSERT INTO MyLargeTable SELECT * FROM OtherTable
    SET IDENTITY_INSERT MyLargeTable OFF
    

    first you enable inserting identity values, than you copy the records, then you enable the identity column again.

    But this won't work neither. SQL server won't accept the * in this case. You have to explicitly include the Id in the script, like :

    SET IDENTITY_INSERT MyLargeTable ON
    INSERT INTO MyLargeTable (Id, co1, col2, ...., col80) SELECT Id, co1, col2, ...., col80 FROM OtherTable
    SET IDENTITY_INSERT MyLargeTable OFF
    

    So we're back from where we started.

    The easiest way is to right click the table in Management Studio, let it generate the INSERT and SELECT scripts, and edit them a little to let them work together.

提交回复
热议问题