在数据插入脚本中如何将父记录的 id 放入子记录中? [英] In data Insert script how to put parent record's id in child record?

查看:29
本文介绍了在数据插入脚本中如何将父记录的 id 放入子记录中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个涉及父表和子表的数据库插入脚本.

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

父记录的自动生成的 id 将作为参考键插入到子记录中.

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

问题是我不知道在脚本中如何告诉 SQL Server 使用子表记录中插入的父记录的 id 作为参考.请帮助我如何将父 ID 放入子插入语句中.

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.

推荐答案

在代码顶部执行以下操作:

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

检索最近插入父表的 ID.

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;

(我只是编造了 valueA 等——你知道你插入到孩子中的样子,只要确保将 parent_id 与 @parent_id 匹配即可.

(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.

这篇关于在数据插入脚本中如何将父记录的 id 放入子记录中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆