下面的示例捕获从 merge 语句的 output 子句返回的数据,并将该数据插入到另一个表中。 merge 语句根据在 salesorderdetail 表中处理的订单更新 productinventory 表的 quantity 列。 本示例捕获已更新的行并将这些行插入到用于跟踪库存变化的另一个表中。
下面的示例捕获从 merge 语句的 output 子句返回的数据,并将该数据插入到另一个表中。 merge 语句根据在 salesorderdetail 表中处理的订单更新 productinventory 表的 quantity 列。 本示例捕获已更新的行并将这些行插入到用于跟踪库存变化的另一个表中。
use adventureworks2012;gocreate table production.updatedinventory (productid int not null, locationid int, newqty int, previousqty int, constraint pk_inventory primary key clustered (productid, locationid));goinsert into production.updatedinventoryselect productid, locationid, newqty, previousqty from( merge production.productinventory as pi using (select productid, sum(orderqty) from sales.salesorderdetail as sod join sales.salesorderheader as soh on sod.salesorderid = soh.salesorderid and soh.orderdate between '20030701' and '20030731' group by productid) as src (productid, orderqty) on pi.productid = src.productid when matched and pi.quantity - src.orderqty >= 0 then update set pi.quantity = pi.quantity - src.orderqty when matched and pi.quantity - src.orderqty <= 0 then delete output $action, inserted.productid, inserted.locationid, inserted.quantity as newqty, deleted.quantity as previousqty) as changes (action, productid, locationid, newqty, previousqty) where action = 'update';go