Reputation: 3490
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?
Upvotes: 1
Views: 212
Reputation: 503
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.
Upvotes: 3