我需要在sql server 2008中合并两个表,通过productid字段过滤源和目标,假设我有一个源表@source(productid,userid)和@target具有相同的结构,我需要合并两个表,但仅适用于具有指定productid的记录。
上面的示例确定我只需要知道是否有更好的方法只删除productId = @ productId与源不匹配的记录与添加“和TARGET.productid = @productid”运算符相比较 不符合来源?
感谢。
declare @productid int = 1
declare @source table (productid int, userid int)
declare @target table (productid int, userid int)
insert into @source (productid , userid ) values(1,1)
insert into @source (productid , userid ) values(1,2)
insert into @source (productid , userid ) values(1,3)
insert into @source (productid , userid ) values(2,1)
insert into @source (productid , userid ) values(2,2)
insert into @source (productid , userid ) values(2,3)
insert into @target (productid , userid ) values(1,4)
insert into @target (productid , userid ) values(2,5)
insert into @target (productid , userid ) values(3,1)
insert into @target (productid , userid ) values(4,1);
WITH n (productid , userid )
AS
(
select productid , userid from @source where productid = @productid
)
MERGE @target AS TARGET
USING n AS SOURCE
ON (TARGET.productid = SOURCE.productid and TARGET.userid = SOURCE.userid)
WHEN NOT MATCHED BY TARGET THEN
INSERT (productid , userid)
VALUES (SOURCE.productid, SOURCE.userid)
WHEN NOT MATCHED BY SOURCE and TARGET.productid = @productid THEN
DELETE;
select * from @target order by 1,2
答案 0 :(得分:2)
目标表不必是SQL Server中的基表。它可以是CTE,派生表,甚至是视图。
旧:
MERGE @target AS TARGET
新:
MERGE (SELECT * FROM @target WHERE ArbitraryCondition) AS TARGET
使用ArbitraryCondition
按您喜欢的方式按productid
进行过滤。
答案 1 :(得分:0)
你应该避免使用 MERGE语句。你应该避免阅读Aaron Bertrand的这篇文章 Use Caution with SQL Server's MERGE Statement
。< / p>
您可以使用简单连接或EXISTS执行此操作。见下文..
插入声明
INSERT INTO Target (productid , userid)
SELECT S.productid , S.userid
FROM Source s LEFT JOIN Target T
ON T.productid = S.productid AND T.userid = S.userid
WHERE S.userid IS NULL OR S.productid IS NULL
AND productid = -- Specify your targeted Ids
删除语句
DELETE FROM S
FROM Source S LEFT JOIN Target T
ON T.productid = S.productid AND T.userid = S.userid
WHERE S.userid IS NULL OR S.productid IS NULL