What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

后端 未结 7 1317
灰色年华
灰色年华 2020-11-22 06:49

I know Scope_Identity(), Identity(), @@Identity, and Ident_Current() all get the value of the identity column, but I woul

7条回答
  •  太阳男子
    2020-11-22 07:05

    Scope means the code context that performs the INSERT statement SCOPE_IDENTITY(), as opposed to the global scope of @@IDENTITY.

    CREATE TABLE Foo(
      ID INT IDENTITY(1,1),
      Dummy VARCHAR(100)
    )
    
    CREATE TABLE FooLog(
      ID INT IDENTITY(2,2),
      LogText VARCHAR(100)
    )
    go
    CREATE TRIGGER InsertFoo ON Foo AFTER INSERT AS
    BEGIN
      INSERT INTO FooLog (LogText) VALUES ('inserted Foo')
      INSERT INTO FooLog (LogText) SELECT Dummy FROM inserted
    END
    
    INSERT INTO Foo (Dummy) VALUES ('x')
    SELECT SCOPE_IDENTITY(), @@IDENTITY 
    

    Gives different results.

提交回复
热议问题