1

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?

Aishwarya Shiva
  • 3,460
  • 15
  • 58
  • 107
  • possible duplicate of [Stored Procedure Issue](http://stackoverflow.com/questions/8986278/stored-procedure-issue) – Tanner Apr 21 '15 at 14:33

1 Answers1

6

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();
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235