2

I'm worndering how I can add 2 rows, of which 1 depends on another, in 1 transaction.

INSERT INTO users (username) VALUES ('malcom.reynolds')

INSERT INTO spaceships (name, owner) 
VALUES ('Serenity', <<Malcom Reynold's row ID>>)

Reason I an doing is that the library I'm using does not return the rowid, and I need to commit the transaction as less as possible as I'm adding over a few million records!

Just for the record I'm using:

  • SQL Server 2008
  • Python
  • pyodbc

Any idea? Would be really awesome :)

0

4 Answers 4

4

You can do this in one batch statement:

declare @key as int;
insert into users (username)
values ('malcom.reynolds');
set @key = (select scope_identity());
insert into spaceships (name, owner)
values ('Serenity', @key)
1
  • thanks for adding the declare line, it worked perfectly! :)
    – RadiantHex
    Dec 16, 2010 at 13:13
4

Look at http://msdn.microsoft.com/en-us/library/aa259185%28SQL.80%29.aspx

INSERT INTO users (username) VALUES ('malcom.reynolds');

INSERT INTO spaceships (name, owner) 
VALUES ('Serenity', SCOPE_IDENTITY() )
4

You can use the T-SQL scope_identity to return the new ID from the first INSERT statement.

Before your first INSERT, declare a variable to hold the value of the new ID:

DECLARE @ReturnValue int;

Right after your first INSERT, add this to set the value of that variable:

SELECT @ReturnValue = scope_identity()

Then, you can use the @ReturnValue variable in your second INSERT in place of :

INSERT INTO spaceships (name, owner) 
VALUES ('Serenity', @ReturnValue)
2
  • thanks for your awesome reply, it did not work initially as I had to declare the variable and I am a bit inexperienced with T-SQL. Thanks for the explanations :D
    – RadiantHex
    Dec 16, 2010 at 13:14
  • @RadiantHex: Thanks for the feedback. I've updated my example for future readers.
    – DOK
    Dec 16, 2010 at 13:27
2

Or you can use OUTPUT. This is hadnier when you need to return more than one field or are doing a multitrow insert to begin with. You can use a table variable if you are doing multiple rows instead of an int variable.

DECLARE @key int
insert into users (username)
output inserted.userid 
values ('malcom.reynolds'); 

insert into spaceships (name, owner) 
values ('Serenity', @key) 

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.