SQL Server插入语句使用INSERTED获取新ID和现有ID
我正在将一个 sql server 数据库中的记录插入到另一个数据库中。我需要获取新插入的 id 并更新源表上的字段。我可以使用 INSERTED 选项获取新 ID,没有问题。但是,我似乎无法从源表中获取 ID。目标表没有源 ID 字段。源表是一个转换表,我不想用转换字段污染目标表。这可能是不可能的,但我想我应该先和你们确认一下。
drop table #Table1
CREATE TABLE #Table1
(
Table1ID INT,
Table2ID INT,
NAME VARCHAR(32)
)
INSERT INTO #Table1
VALUES
(1, NULL, 'Fred')
,(2, NULL, 'Tom')
,(3, NULL, 'Sally')
--ok, im inserting into #Table2
drop table #Table2
CREATE TABLE #Table2
(
[Table2ID] [int] IDENTITY(1,1) NOT NULL,
NAME VARCHAR(32)
)
--THE RUB, I want to insert Table2ID into table3
--along with Table1ID. I cannot seem to reference table1
--Any Ideas?
insert into #Table2(NAME)
OUTPUT INSERTED.Table2ID, T.Table1ID into #Table3
select Name from #Table1 T
I'm inserting records from one sql server db into another. I need to get the newly inserted id and update a field on the source table. I can get the new ID with INSERTED option no problem. However, I cannot seem to get the ID from the source table. The destination table does not have a field for the source's ID. The source table is a conversion table and I do not want to pollute the destination table with conversion fields. This may not be possible but I thought I'd first check with you guys.
drop table #Table1
CREATE TABLE #Table1
(
Table1ID INT,
Table2ID INT,
NAME VARCHAR(32)
)
INSERT INTO #Table1
VALUES
(1, NULL, 'Fred')
,(2, NULL, 'Tom')
,(3, NULL, 'Sally')
--ok, im inserting into #Table2
drop table #Table2
CREATE TABLE #Table2
(
[Table2ID] [int] IDENTITY(1,1) NOT NULL,
NAME VARCHAR(32)
)
--THE RUB, I want to insert Table2ID into table3
--along with Table1ID. I cannot seem to reference table1
--Any Ideas?
insert into #Table2(NAME)
OUTPUT INSERTED.Table2ID, T.Table1ID into #Table3
select Name from #Table1 T
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能用 INSERT 来做到这一点(因为它缺少自己的 FROM 子句),但你可以用 MERGE 来做到这一点:
You cannot do it with INSERT (sine it lacks a FROM clause of its own) but you can do it with MERGE:
将转化 ID 字段放入表中。这不是污染桌子,而是妥善处理问题。另外,您可以在输出子句中将其取回。而且它也将使更新子表变得更加简单。我认为没有理由不这样做,除非你有在生产代码中使用 Select * 的糟糕开发人员。
Put the conversion id field in the table. This is not polluting the table, it is handling the problem properly. Plus you can then get it back out in the output clause. And it will make it simpler to update child tables as well. I see no reason at all not to do this unless you have poor developers who use Select * in production code.