Primary key value after insertion of row in SQL Server 2005

后端 未结 2 1391
抹茶落季
抹茶落季 2021-01-21 02:10

In SQL Server 2005 I am inserting a row into a table using a stored procedure and I want to fetch the new primary key value just after inserting that row. I am using following

相关标签:
2条回答
  • 2021-01-21 02:59

    If you have an Identity column as primary key you should use SCOPE_IDENTITY()

    You could also use the OUTPUT Clause to return the ID.

    insert into tableTest(testUserEmail,testUserName) 
    output inserted.ID
    values (@testValue, @testName)
    
    0 讨论(0)
  • 2021-01-21 03:00

    By all means - use the SCOPE_IDENTITY() if your ID column is an INT IDENTITY - only that will give you the correct results!

    The first approach with the MAX(ID) will fail terribly if you have multiple clients inserting rows almost at the same time - you'll get false results back. Don't use that!

    The third approach might fail if another entry with the same values for E-Mail and name already exists.

    Also, as a side-note: you should never use sp_ as your prefix! This is a Microsoft-reserved prefix and has downsides in terms of performance - use something else.

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