Do Inserted Records Always Receive Contiguous Identity Values

前端 未结 5 1746
终归单人心
终归单人心 2020-12-06 14:16

Consider the following SQL:

CREATE TABLE Foo
(
    ID int IDENTITY(1,1),
    Data nvarchar(max)
)

INSERT INTO Foo (Data)
SELECT TOP 1000 Data
FROM SomeOther         


        
5条回答
  •  长情又很酷
    2020-12-06 14:54

    If you want the Identity values for multiple rows use OUTPUT:

    DECLARE @NewIDs table (PKColumn int)
    INSERT INTO Foo (Data)
        OUTPUT INSERTED.PKColumn
        INTO @NewIDs
    SELECT TOP 1000 Data
    FROM SomeOtherTable
    WHERE SomeColumn = @SomeParameter
    

    you now have the entire set of values in the @NewIDs table. You can add any columns from the Foo table into the @NewIDs table and insert those columns as well.

提交回复
热议问题