Reputation: 409
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.
Upvotes: 0
Views: 1632
Reputation: 9566
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
Upvotes: 3