So I will try to explain my problem with pseudo code. But first of all some explanation. I am trying to create simple procedure in SQL that will insert data into three tables, where IDs from table_1
and table_2
have to be passed to table_3
. Not sure how to achieve it. I am using SQL Server.
pseudo code
CREATE PROCEDURE Bla
@arg VARCHAR(1)
AS
INSERT INTO table_1 VALUES(...) -- need id from here
INSERT INTO table_2 VALUES(...) -- and id from here
INSERT INTO table_3 VALUES (..., table_1_id, table_2_id)
As you can guess those IDs are Foreign Keys
in table_3
So I was thinking about doing something like this, after I INSERT
data into table_1
and table_2
@tab1id = SELECT TOP 1 id from table_1 ORDER BY id DESC
@tab2id = SELECT TOP 1 id from table_2 ORDER BY id DESC
INSERT INTO table_3 VALUES (..., @tab1id, @tab2id)
But for some reason I do not think it is good practice. So I googled it and found something like SCOPE_IDENTITY
but not sure how to use it properly, my idea is to do something like:
INSERT INTO table_1 VALUES(...)
@tab1id = SELECT SCOPE_IDENTITY()
INSERT INTO table_2 VALUES(...)
@tab2id = SELECT SCOPE_IDENTITY()
INSERT INTO table_3 VALUES (..., @tab1id, @tab2id)
But not sure if that is good idea, please give some advice.