【问题标题】:tsql return identity values when inserting multiple records into a viewtsql 在向视图中插入多条记录时返回标识值
【发布时间】:2012-05-29 10:27:30
【问题描述】:

我有一种情况,我需要将多条记录/批量插入插入到具有而不是触发器的视图中。如何检索插入的标识值?我尝试使用 OUTPUT 子句从 Inserted 表中检索 Id,但它总是返回 null。

【问题讨论】:

  • 您可以在INSTEAD OF 触发器本身内使用OUTPUT 子句。也许通过条件逻辑检查CONTEXT_INFO 以了解是否调用带有或不带有子句的插入语句。#

标签: sql-server tsql triggers identity


【解决方案1】:

使用此设置。

create table InsteadOf
(
  ID int identity primary key,
  Name varchar(10) not null
)

go

create view v_InsteadOf
as
select ID, Name
from InsteadOf

go

create trigger tr_InsteadOf on InsteadOf instead of insert
as
begin
  insert into InsteadOf(Name)
  select Name
  from inserted
end

声明

insert into v_InsteadOf(Name)
output inserted.*
select 'Name1' union all 
select 'Name2'

会给你一个错误。

Msg 334, Level 16, State 1, Line 4 DML 语句不能有任何启用的触发器,如果​​该语句 包含一个没有 INTO 子句的 OUTPUT 子句。

使用 INTO 子句代替插入。

declare @IDs table(ID int, Name varchar(10))

insert into v_InsteadOf(Name)
output inserted.* into @IDs
select 'Name1' union all 
select 'Name2'

select *
from @IDs

0 作为值而不是null 提供给您。

ID          Name
----------- ----------
0           Name1
0           Name2

您可以将输出子句放在触发器中。

create trigger tr_InsteadOf on InsteadOf instead of insert
as
begin
  insert into InsteadOf(Name)
  output inserted.*
  select Name
  from inserted
end

当您进行插入时,将为您生成输出。

insert into v_InsteadOf(Name)
select 'Name1' union all 
select 'Name2'

结果:

ID          Name
----------- ----------
1           Name1
2           Name2

更新:
要捕获插入语句的输出,您可以使用insert into ... exec (...)

declare @T table
(
  ID int,
  Name varchar(10)
)

insert into @T
exec
  (
    'insert into v_InsteadOf(Name)
     values (''Name1''),(''Name2'')'
  )

【讨论】:

  • 如何将这些返回值存储到表变量中以备后用?下面的查询返回 0 作为插入行的 id。 DECLARE @T TABLE (ID INT, NAME Varchar(10)) INSERT INTO v_InsteadOf(Name) OUTPUT INSERTED.* INTO @T VALUES ('gk'),('gv') SELECT * FROM @T
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
  • 1970-01-01
相关资源
最近更新 更多