简体   繁体   中英

how to insert data in multiple tables using transaction

my first tables unique key is a foreign key in sub-table and i am using transactions in stored procedure ,problem when i use transaction then first tables unique key being inserted shows no value before committing the query and for second table's data insertion i need unique key of row being inserted in first table. i would use a select query with where clause . but my interviewer said tell me some other way to achieve that ,he said he could not write "select where " statement for 100 tables.

In such cases you would use SCOPE_IDENTITY() function to retrieve the identity of the newly inserted row in parent table. Your script should look like this:

begin transaction
declare @parentId int;
insert into ParentTable(Value1, Value2) values('1', '2')

select @parentId = SCOPE_IDENTITY()
insert into ChildTable(ParentId, Value) values(@parentId, '3')
commit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM