views:

304

answers:

3

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.

+4  A: 

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();
Spencer Ruport
I believe scope_identity() is preferred to @@IDENTITY in most situations.
Joel Coehoorn
+1 for Joels note, scoped_identity will handle triggers gracefully (eg. if you have an insert trigger, your @@identity can become bogus)
Sam Saffron
That did the trick thanks, I'm using SQLServer 2005 which does seem to support scope_identity().
Kenny
Kenny, scope_identity() is supported by SQLServer 2005 and even 2000. It is safer to use than @@identity.
kristof
+4  A: 

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

beach
+2  A: 

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.

Cade Roux