如何使用OUTPUT获取标识列的值

编程入门 行业动态 更新时间:2024-10-23 07:15:30
如何使用OUTPUT获取标识列的值 - SQL Server(How to get a value of identity column using 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?

最满意答案

这个实际上有效。

declare @tmp_table table(seq int identity, id int, int_val int); insert into test(data) output inserted.data into @tmp_table(int_val) values (11),(12),(13); update @tmp_table set id = seq + @@identity - @@rowcount select * from @tmp_table; select top 2 * from test order by id desc;

限制是您必须在表test中没有任何其他会“破坏”@@ identity变量的触发器。

This one actually works.

declare @tmp_table table(seq int identity, id int, int_val int); insert into test(data) output inserted.data into @tmp_table(int_val) values (11),(12),(13); update @tmp_table set id = seq + @@identity - @@rowcount select * from @tmp_table; select top 2 * from test order by id desc;

The restriction is that you must NOT have any other triggers on the table test that would "corrupt" the @@identity variable.

更多推荐

本文发布于:2023-07-17 13:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1144979.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   标识   OUTPUT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!