简体   繁体   中英

Inserting a row in a table and storing its scope identity in a variable in a stored procedure

I am a newbie in stored procedure and knows only basics of SQL. With the help of some SO questions I was able to figure out that SCOPE_IDENTITY() function can be used to get recently added row's identity value. Now I am trying to insert a row in a table using a stored procedure and I want that the identity of this newly inserted row must be assigned to a stored procedure's variable. Following is the code:

DECLARE @retID int = -1
SET @retID = (INSERT INTO [InfoValues]([InfoID],[Value],[UserID],[DateAdded],[DateUpdated]) VALUES(@item2,@item,@UserID,GETDATE(), GETDATE()); SELECT SCOPE_IDENTITY())

But this code is showing a syntax error at INSERT clause. So what is the correct way to do it?

You're close. You need to set the variable after the insert occurs.

DECLARE @retID int = -1;

INSERT INTO [InfoValues]
    ([InfoID],[Value],[UserID],[DateAdded],[DateUpdated])     
    VALUES
    (@item2,@item,@UserID,GETDATE(), GETDATE()); 

SET @retID = SCOPE_IDENTITY();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM