如何使用 OUTPUT 获取标识列的值 - SQL Server
我有一个表和一个触发器。
create table test(id int not null identity(1,1) primary key, data int);
create trigger insteadTestInsert ON test INSTEAD OF INSERT
AS
BEGIN
INSERT INTO test(data) select data FROM inserted;
END;
启用触发器后,以下查询
declare @tmp_table table(id int, int_val int);
insert into test(data)
output inserted.* into @tmp_table
values (10);
select * from @tmp_table;
返回 id = 0, int_val = 10 。
如果我禁用(或删除)触发器,查询将返回 id
的正确值。
如何使OUTPUT
将正确的结果插入表变量中?
I have a table and a trigger
create table test(id int not null identity(1,1) primary key, data int);
create trigger insteadTestInsert ON test INSTEAD OF INSERT
AS
BEGIN
INSERT INTO test(data) select data FROM inserted;
END;
When trigger is enabled, the following query
declare @tmp_table table(id int, int_val int);
insert into test(data)
output inserted.* into @tmp_table
values (10);
select * from @tmp_table;
returns id = 0, int_val = 10 .
If I disable(or drop) the trigger, the query returns the proper value of id
.
How to make OUTPUT
insert proper results into table variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 MSDN
所以问题是在执行触发器之前插入没有设置 id。
即使像这样删除触发器的内容,
您也会看到
inserted
仍然填充,尽管表中没有inserted
任何内容。基本上,output
语句中的inserted
与触发器内部的inserted
相匹配。From MSDN
So the problem is that before your trigger was executed inserted didn't have id set.
Even if remove content of the trigger like this
you will see that
inserted
is still populated although nothing wasinserted
into the table. Basicallyinserted
inoutput
statement matchesinserted
inside of the trigger.这个确实有效。
限制是表
test
上不能有任何其他会“损坏”@@identity 变量的触发器。This one actually works.
The restriction is that you must NOT have any other triggers on the table
test
that would "corrupt" the @@identity variable.这是一个 hack,但它有效:
请参阅 http://msdn.microsoft.com /en-us/library/ms190315.aspx 了解有关使用 @@IDENTITY 的详细信息。
This is a hack, but it works:
See http://msdn.microsoft.com/en-us/library/ms190315.aspx for details on using @@IDENTITY.