基于集合的插入到具有 1 到 0-1 关系的两个表中
我有两个表,第一个表的主键是身份,第二个表的主键不是身份,但该键具有回到第一个表的主键的外键约束。
如果我一次插入一条记录,我可以使用 Scope_Identity 获取刚刚插入表 1 中的 pk 的值,并将其插入到第二个表中。
我的问题是我有很多记录来自我想要插入到两个表中的选择,我无法想到基于集合的方法来执行这些插入。
我当前的解决方案是使用游标,插入第一个表,使用scope_identity获取密钥,插入第二个表,重复。
我是否缺少非光标解决方案?
I have two tables, the first has a primary key that is an identity, the second has a primary key that is not, but that key has a foreign key constraint back to the first table's primary key.
If I am inserting one record at a time I can use the Scope_Identity to get the value for the pk just inserted in table 1 that I want to insert into the second table.
My problem is I have many records coming from selects I want to insert in both tables, I've not been able to think of a set based way to do these inserts.
My current solution is to use a cursor, insert in the first table, get key using scope_identity, insert into second table, repeat.
Am I missing a non-cursor solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,在网上查找输出子句。
Yes, Look up the output clause in Books online.
本周我遇到了这个问题:有人在自然使用键的模式中引入了一个带有无意义代理键的表。 毫无疑问,我很快就会解决这个问题:)在那之前,我正在通过创建一个数据表来解决这个问题:这可以是永久或临时基表或派生表(见下文),无论如何,这应该满足您对基于集合的解决方案的需求。 在此表和自然键上带有
IDENTITY
列的表之间使用联接来查找自动生成的值。 这是一个简短的例子:I had this problem just this week: someone had introduced a table with a meaningless surrogate key into the schema where naturally keys are used. No doubt I'll fix this soon :) until then, I'm working around it by creating a table of data to
INSERT
from: this could be a permanent or temporary base table or a derived table (see below), which should suit your desire for a set-based solution anyhow. Use a join between this table and the table with theIDENTITY
column on the natural key to find out the auto-generated values. Here's a brief example: