Best way to get identity of inserted row?

后端 未结 14 2470
醉梦人生
醉梦人生 2020-11-21 07:06

What is the best way to get IDENTITY of inserted row?

I know about @@IDENTITY and IDENT_CURRENT and SCOPE_IDENTITY

14条回答
  •  自闭症患者
    2020-11-21 07:45

    When you use Entity Framework, it internally uses the OUTPUT technique to return the newly inserted ID value

    DECLARE @generated_keys table([Id] uniqueidentifier)
    
    INSERT INTO TurboEncabulators(StatorSlots)
    OUTPUT inserted.TurboEncabulatorID INTO @generated_keys
    VALUES('Malleable logarithmic casing');
    
    SELECT t.[TurboEncabulatorID ]
    FROM @generated_keys AS g 
       JOIN dbo.TurboEncabulators AS t 
       ON g.Id = t.TurboEncabulatorID 
    WHERE @@ROWCOUNT > 0
    

    The output results are stored in a temporary table variable, joined back to the table, and return the row value out of the table.

    Note: I have no idea why EF would inner join the ephemeral table back to the real table (under what circumstances would the two not match).

    But that's what EF does.

    This technique (OUTPUT) is only available on SQL Server 2008 or newer.

    Edit - The reason for the join

    The reason that Entity Framework joins back to the original table, rather than simply use the OUTPUT values is because EF also uses this technique to get the rowversion of a newly inserted row.

    You can use optimistic concurrency in your entity framework models by using the Timestamp attribute:

提交回复
热议问题