我可以将这两个几乎相同的MERGE语句合并为一个吗?

时间:2012-08-03 00:33:24

标签: sql sql-server sql-server-2008

我有一种感觉,我在这个问题上花了太多时间而且被蒙蔽了......希望一双新鲜的眼睛可以帮助指出一个简单的错误!

这是我认为应该起作用的MERGE声明:

无效:

MERGE assignment_tbl AS target
USING (SELECT 1 s) AS source
ON target.id = @id
   AND target.id1 = @id1
   AND target.id2 = @id2
WHEN matched AND NOT (target.iFeeScope = @iFeeScope OR target.nFeeAmount = @nFeeAmount) AND (target.bActive = 1) THEN
  UPDATE SET target.dLastUpdated = @dNow,
             target.dDisabled = @dNow,
             target.bActive = 0;

问题出在我的WHEN matched AND NOT语句中:(target.iFeeScope = @iFeeScope OR target.nFeeAmount = @nFeeAmount),我发现的唯一方法就是将语句分成两个独立的(几乎相同的)块:

工作(但效率低下):

MERGE assignment_tbl AS target
USING (SELECT 1 s) AS source
ON target.id = @id
   AND target.id1 = @id1
   AND target.id2 = @id2
WHEN matched AND NOT (target.iFeeScope = @iFeeScope) AND (target.bActive = 1) THEN
  UPDATE SET target.dLastUpdated = @dNow,
             target.dDisabled = @dNow,
             target.bActive = 0;

MERGE assignment_tbl AS target
USING (SELECT 1 s) AS source
ON target.id = @id
   AND target.id1 = @id1
   AND target.id2 = @id2
WHEN matched AND NOT (target.nFeeAmount = @nFeeAmount) AND (target.bActive = 1) THEN
  UPDATE SET target.dLastUpdated = @dNow,
             target.dDisabled = @dNow,
             target.bActive = 0; 

我需要在原始语句中更改以获得以下两个语句的结果?

提前谢谢大家!

2 个答案:

答案 0 :(得分:0)

怎么样:

WHEN matched AND target.iFeeScope != @iFeeScope AND target.nFeeAmount != @nFeeAmount AND (target.bActive = 1) THEN

答案 1 :(得分:0)

我自己解决了......认为这是AND / NOT逻辑的一个问题!

MERGE assignment_tbl AS target
USING (SELECT 1 s) AS source
ON target.id = @id
   AND target.id1 = @id1
   AND target.id2 = @id2
   AND target.bActive = 1
WHEN matched AND (NOT (target.iFeeScope = @iFeeScope)) 
             OR (NOT (target.nFeeAmount = @nFeeAmount)) THEN
  UPDATE SET target.dLastUpdated = @dNow,
             target.dDisabled = @dNow,
             target.bActive = 0;