sqlsql-serverinsertscope-identity

Consistency when using SCOPE_IDENTITY() in output


I want to execute a SQL query that would return the current identity id of the row that was added to the table:

DECLARE @id int
DECLARE @tblOutput table (id int)

INSERT INTO tblStudent(Name, Family, age, test)
OUTPUT inserted.id into @tblOutput
VALUES('ashghar', 'farhadi', 321, 135)

SELECT @id = id from @tblOutput

Now my question is it the returned id for my current inserted row or is it the id of the last inserted row?

I mean can I trust it for using as foreign key?


Solution

  • Both output inserted and SCOPE_IDENTITY will give you the id from the row just inserted by your last statement. So yes you can use it as a foreign key.