Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add two rows with foreign key - SQL

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 :)

like image 735
RadiantHex Avatar asked Feb 11 '26 22:02

RadiantHex


1 Answers

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)
like image 66
D'Arcy Rittich Avatar answered Feb 13 '26 14:02

D'Arcy Rittich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!