Jump to content
Xtreme .Net Talk

Recommended Posts

Posted
OK, I'm assuming there's a way to do this in SQL Server but I've never needed to do it before and can't seem to find the exact syntax. I need to create a new record in a table and get back the key field that was created. Can I do this with one statement?
Here's what I'm up to.
Posted
INSERT Employees (FirstName, LastName) VALUES ('test', 'Test')

SELECT @@IDENTITY

Be careful with @@IDENTITY. This system variable allways contains the last inserted key of the executed command in the actual session. This means, if the insert triggers another insert into a table with an identity column, it will return that key.

 

Better use the function SCOPE_IDENTITY(). It returns the key only out of the actual scope in the actual session. You use it the same way:

INSERT Employees (FirstName, LastName) VALUES ('test', 'Test');
SELECT SCOPE_IDENTITY()

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...