SQL - Inserting a row and returning primary key

前端 未结 8 1127
南笙
南笙 2020-12-01 18:07

I have a little witty problem. Say, I inserted a row with some data in a table where a primary key is present. How would one \"SELECT\" the primary key of the row one just i

相关标签:
8条回答
  • 2020-12-01 18:23

    For MS SQL Server:

    SCOPE_IDENTITY() will return you the last generated identity value within your current scope:

    SELECT SCOPE_IDENTITY() AS NewID
    
    0 讨论(0)
  • 2020-12-01 18:36

    SQL Server:

    You can use @@IDENTITY. After an insert statement, you can run:

    select @@identity
    

    This will give you the primary key of the record you just inserted. If you are planning to use it later, I suggest saving it:

    set @MyIdentity = @@identity
    

    If you are using this in a stored procedure and want to access it back in your application, make sure to have nocount off.

    0 讨论(0)
提交回复
热议问题