如何在T-SQL中使用OUTPUT删除和插入记录?

时间:2019-05-09 23:09:53

标签: sql-server tsql

我正在尝试删除一些记录并同时插入到其他表中。删除时,它是该表上的一个自联接,它检查一些条件。我想使用OUTPUT子句进行删除和插入操作。

代码:

DELETE dbo.Test
OUTPUT DELETED.Recipient_Key,
       DELETED.Home_Dt,
       DELETED.Batch_No,
       DELETED.Brand_Cd,
       DELETED.Campaign_Cd,
       DELETED.Campaign_Nm,
       DELETED.CampaignType_Cd
INTO dbo.Error
FROM dbo.Test AS PR1
    INNER JOIN Staging.dbo.Test AS PR2
        ON PR2.Recipient_Key = PR1.Recipient_Key
           AND PR2.Batch_No = PR1.Batch_No
           AND PR2.Home_Dt <> PR1.Home_Dt;

1 个答案:

答案 0 :(得分:0)

使用自我联接,您需要指定一个别名。

drop table if exists #test;
create table #test (
      Id int not null primary key clustered identity(1, 1)
    , SomeColumn varchar(255) not null
);

drop table if exists #error;
create table #error (
      Id int not null primary key clustered
    , SomeColumn varchar(255) not null
);

insert into
    #test (SomeColumn)
values
('A'), ('B'), ('C');



select * from #test;
select * from #error;

delete a
output
    Deleted.Id, Deleted.SomeColumn
into
    #error (Id, SomeColumn)
from
    #test as a
inner join
    #test as b
    on
        a.Id = b.Id
        and a.Id % 2 = 1;

select * from #test;
select * from #error;