带JOIN的条件UPDATE语句

时间:2016-08-04 15:30:15

标签: sql sql-server

我尝试根据另一个表Plan_Status,列main的值更新列Days_At_Step
以下说明有效,但是,如何我会把它作为条件陈述吗?
或者,我可以使用另一种策略吗?

我觉得比使用具有不同WHERE条件的三个相同语句更好的方法。

  UPDATE controlState 
  SET Plan_Status=1 
  FROM controlState JOIN main ON main.Cscc = controlState.Cscc 
  WHERE Days_At_Step < 2;

  UPDATE controlState 
  SET Plan_Status=2 
  FROM controlState JOIN main ON main.Cscc = controlState.Cscc 
  WHERE (Days_At_Step >= 2 OR Days_At_Step < 4);

  UPDATE controlState 
  SET Plan_Status=3 
  FROM controlState JOIN main ON main.Cscc = controlState.Cscc 
  WHERE Days_At_Step > 4;

3 个答案:

答案 0 :(得分:0)

我想这可行:

UPDATE controlState 
SET Plan_Status = 
  CASE WHEN Days_At_Step < 2 THEN 1
       WHEN (Days_At_Step >= 2 OR Days_At_Step < 4) THEN 2
       WHEN Days_At_Step > 4 THEN 3 END
FROM controlState JOIN main ON   main.Cscc = controlState.Cscc

答案 1 :(得分:0)

这应该有效:

UPDATE controlState 
SET Plan_Status = CASE 
                  WHEN Days_At_Step < 2 THEN 1
                  WHEN (Days_At_Step >= 2 OR Days_At_Step < 4) THEN 2
                  WHEN Days_At_Step > 4 THEN 3 END
FROM controlState JOIN main ON main.Cscc = controlState.Cscc

答案 2 :(得分:0)

这三个where条款涵盖Days_At_Step可能获得的所有可能值,因此您根本不需要where条款。相反,您可以将此逻辑移动到case表达式:

UPDATE controlState 
SET    Plan_Status = CASE WHEN Days_At_Step < 2 THEN 1 
                          WHEN (Days_At_Step >= 2 OR Days_At_Step < 4) THEN 2
                          ELSE 3
                     END
FROM   controlState 
JOIN   main ON main.Cscc = controlState.Cscc;