Do Inserted Records Always Receive Contiguous Identity Values

前端 未结 5 1752
终归单人心
终归单人心 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 15:13

    Yes, they will be contiguous because the INSERT is atomic: complete success or full rollback. It is also performed as a single unit of work: you wont get any "interleaving" with other processes

    However (or to put your mind at rest!), consider the OUTPUT clause

    DECLARE @KeyStore TABLE (ID int NOT NULL)
    
    INSERT INTO Foo (Data)
    OUTPUT INSERTED.ID INTO @KeyStore (ID) --this line
    SELECT TOP 1000 Data
    FROM SomeOtherTable
    WHERE SomeColumn = @SomeParameter
    

提交回复
热议问题