Getting new IDs after insert

前端 未结 4 1803
我在风中等你
我在风中等你 2020-12-07 16:46

I\'m inserting a bunch of new rows into a table which is defined as follows:

CREATE TABLE [sometable](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [someval] s         


        
4条回答
  •  无人及你
    2020-12-07 17:25

    Use the OUTPUT functionality to grab all the INSERTED Id back into a table.

    CREATE TABLE MyTable
    (
        MyPK INT IDENTITY(1,1) NOT NULL,
        MyColumn NVARCHAR(1000)
    )
    
    DECLARE @myNewPKTable TABLE (myNewPK INT)
    
    INSERT INTO 
        MyTable
    (
        MyColumn
    )
    OUTPUT INSERTED.MyPK INTO @myNewPKTable
    SELECT
        sysobjects.name
    FROM
        sysobjects
    
    SELECT * FROM @myNewPKTable
    

提交回复
热议问题