这表明如何从MERGE语句记录输出数据。请注意,OUTPUT子句在MERGE中的所有分支上运行,包括UPDATE和INSERT部分。然后使用inserted.id和deleted.id之间的不匹配来确定实际插入的内容。 OUTPUT子句展示了如何发扬从inserted
虚拟表name
列。
use tempdb;
-- create the test tables and table type
create table dbo.FirstTable (
ID int identity primary key,
NAME sysname,
myDATE datetime);
GO
create table dbo.SecondTable (
ID int primary key,
myDATE datetime,
NAME sysname);
GO
create type TTVP as TABLE(ID int, NAME sysname);
GO
-- create the procedure
CREATE PROCEDURE dbo.SP1
@p as TTVP readonly
AS
SET NOCOUNT ON;
create table #cache (new_id int primary key, old_id int, name sysname);
merge into dbo.firsttable tp
using @p ps on tp.id = ps.id
when matched then
update
set tp.name = ps.name,
tp.mydate = getdate()
when not matched then
insert (name, mydate)
values (ps.name, getdate())
output inserted.id, deleted.id, inserted.name into #cache;
insert into dbo.secondtable (id, mydate, name)
select new_id, getdate(), name
from #cache
where old_id is null;
GO
-- set up some test data (2 rows)
truncate table dbo.FirstTable;
insert dbo.FirstTable values ('abc', getdate());
insert dbo.FirstTable values ('ghi', getdate()-1);
GO
-- execute the procedure
declare @p TTVP;
insert @p values (1, 'abc'),(2, 'xyz'),(3, 'def');
exec dbo.SP1 @p;
-- check the results
select * from dbo.firsttable
select * from dbo.secondtable
@Richard固定的...... – NoviceDeveloper 2013-04-05 01:12:34
我要迂腐约2两件事:1 MERGE不适[标签:SQL服务器2005年。 2.如果您还有其他问题,请随时再提问 - 这样做没有任何费用。欢迎来到StackOverflow! (我已经更新。但是我的回答) – RichardTheKiwi 2013-04-05 01:48:51
真的有人下来投票呢? – NoviceDeveloper 2013-04-05 12:05:04