Machaira Posted June 14, 2005 Posted June 14, 2005 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? Quote Here's what I'm up to.
Administrators PlausiblyDamp Posted June 14, 2005 Administrators Posted June 14, 2005 After doing an insert you can always get the value from @@IDENTITY Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Machaira Posted June 15, 2005 Author Posted June 15, 2005 Can you elaborate on this? How would the SQL look? I'm a relative newb in SQL Server. :) Thanks for the reply. Quote Here's what I'm up to.
Administrators PlausiblyDamp Posted June 15, 2005 Administrators Posted June 15, 2005 If you run the following against Northwind you should see what I mean. INSERT Employees (FirstName, LastName) VALUES ('test', 'Test') SELECT @@IDENTITY Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Machaira Posted June 15, 2005 Author Posted June 15, 2005 I'll give it a try. Thanks much! Quote Here's what I'm up to.
APaule Posted June 15, 2005 Posted June 15, 2005 INSERT Employees (FirstName, LastName) VALUES ('test', 'Test') SELECT @@IDENTITYBe 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() Quote
michael_hk Posted June 16, 2005 Posted June 16, 2005 APaule, thanks for sharing. I always used @@IDENTITY before. :) Quote There is no spoon. <<The Matrix>>
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.