2012-05-29 27 views
1

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

+1

您可以使用内部的'OUTPUT'条款'INSTEAD OF'触发自己。或许使用条件逻辑检查'CONTEXT_INFO'来知道是否使用或不使用子句来调用插入语句。# –

回答

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' 

会给你一个错误。

消息334,级别16,状态1,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

如何将这些返回的值存储到表变量以供以后使用?下面的查询返回0作为插入行的id。 DECLARE @T TABLE(ID INT,NAME VARCHAR(10)) INSERT INTO v_InsteadOf(名称) OUTPUT插入。* INTO @T VALUES( 'GK'),( 'GV') SELECT * FROM @ T – vgk

+0

@vgk - 更新了我的答案。 –