0

I'm trying to create a bunch of entries in a database with a single script and the problem I'm encountering is how to reference the generated primary key of the previous entry I created.

For example if I created a customer, then tried to create an order for that customer, how do I get the primary key generated for the customer?

I'm using SQLServer.

3 Answers 3

4

Like so:

DECLARE @customerid int;
INSERT INTO customers(name) VALUES('Spencer');
SET @customerid = @@IDENTITY;

EDIT:

Apparently it needs to be SCOPE_IDENTITY() in order to function as expected with triggers.

DECLARE @customerid int;
INSERT INTO customers(name) VALUES('Spencer');
SET @customerid = SCOPE_IDENTITY();
Sign up to request clarification or add additional context in comments.

4 Comments

I believe scope_identity() is preferred to @@IDENTITY in most situations.
+1 for Joels note, scoped_identity will handle triggers gracefully (eg. if you have an insert trigger, your @@identity can become bogus)
That did the trick thanks, I'm using SQLServer 2005 which does seem to support scope_identity().
Kenny, scope_identity() is supported by SQLServer 2005 and even 2000. It is safer to use than @@identity.
4

If available in your version, use SCOPE_IDENTITY() instead. Safer than @@IDENTITY.

Comments

2

If you are inserting multiple rows at once, you can get all the identities (for use in, say, creating related records) by using the OUTPUT INTO feature of SQL Server 2005 or later.

This could avoid you having to write loops and cursors etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.