In data Insert script how to put parent record's id in child record?

社会主义新天地 提交于 2019-12-23 01:11:13

问题


I m creating a database insert script which involve a parent and a child table.

Parent record's auto-generated id will be inserted to child record as reference key.

Question is I don't know in script how to tell SQL server to use inserted parent records's id in child table record as reference. Please help me how to put parent id in child insert statement.


回答1:


At the top of your code do this:

DECLARE @parent_id int

Then, immediately after you do the insert into the parent table, do this:

SELECT @parent_id = SCOPE_IDENTITY()

That retrieves the id of the most recent insert into the parent table.

Finally, in your insert into the child table, do something like this:

INSERT INTO child_table (parent_id, colA, colB, colC) SELECT @parent_id, valueA, valueB, valueC;

(I just made up valueA, etc.--you know what your insert into the child will look like, just make sure to match up parent_id with @parent_id.




回答2:


In case you have bulk inserts in your table you can grab inserted ids directly in insert statement and then use those values for further processing of child entities. For example:

Declare @out Table(id int, some_col int)

Insert Into SomeTable(some_col)
Output inserted.id, inserted.some_col Into @out
Values(5),(6)

Now you have in your table variable inserted identities along with some other column values if you need.

In case of seperate inserts one by one, you can also use Scope_Identity or @@Identity depending on your logic.




回答3:


may be this works fine

CREATE TABLE PARENT
(
 Pid int primary key identity(1,1)
 ,Pdescription varchar(100)
)

CREATE TABLE Child

(
ChildId int primary key identity(1,1)
,PidcHILD int foreign key references parent(pid )

)
CREATE TABLE #TEMPChild

(
PidcHILD int 
)


BEGIN TRAN
INSERT INTO PARENT 
OUTPUT inserted.Pid 
INTO #TEMPChild(PidcHILD)
VALUES('Record1');

INSERT INTO Child(PidcHILD)-- Add other columns here for child table
SELECT PidcHILD FROM #TEMPChild

COMMIT TRAN 

SELECT * FROM Child
SELECT * FROM  PARENT



回答4:


step-1: get max(pid) form Parent table. step-2: store in variable. step-3: insert this variable into child table .



来源:https://stackoverflow.com/questions/29666689/in-data-insert-script-how-to-put-parent-records-id-in-child-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!