SQL有条件地更新每一行

时间:2014-12-27 18:20:45

标签: sql sql-server

我遇到了一个复杂的情况。我搜索了所有的博客,但找不到任何接近我的期望的答案。我正在运行以下查询:

**Table1                                                        Table2**    
**ID    Status  RptGChng    RptAChng    RptRChng        |    ID    Status**
8614    Green    0             0        0               |    8614   Red
8548    Unknown  0             0        0               |    8548   Amber
2591    Amber    0             0        0               |    2591   Amber
7813    Green    0             0        0               |    7813   Green
8413    Red      0             0        0               |    8413   Red
8183    Green    0             0        0               |    8183   Green
7431    Red      0             0        0               |    7431   Red
7399    Green    0             0        0               |    7399   Red
7776    Unknown  0             0        0               |    7776   Unknown
8609    Green    0             0        0               |    8609   Green
8068    Green    0             0        0               |    8068   Green

如果从表1到表2的id的绿色值发生了变化,RptGChng应该给我一个值1。我需要以这种方式填充RptAChng - > Amber和RptRChng - >红色。 我写的代码如下:

 set [RptGChng]   =
 IIF(([Status]='Green'),1,0)-
 IIF(([Status]=(
 SELECT b.[Status] FROM [Table1] a INNER JOIN [Table2] b  ON
 a.[id]= b.[id] and b.[Status]='Green')),1,0)

1 个答案:

答案 0 :(得分:2)

UPDATE t1
 SET t1.RptGChng = CASE WHEN t1.[Status] = 'Green' AND  t1.[Status] <> t2.[Status] 
                        THEN 1 ELSE t1.RptGChng END 
    ,t1.RptAChng = CASE WHEN t1.[Status] = 'Amber' AND  t1.[Status] <> t2.[Status] 
                        THEN 1 ELSE t1.RptAChng  END 
    ,t1.RptRChng = CASE WHEN t1.[Status] = 'RED'   AND  t1.[Status] <> t2.[Status] 
                        THEN 1 ELSE t1.RptRChng END 
FROM Table1 t1 
INNER JOIN Table2 t2  ON t1.[id]= t2.[id]

由于您使用了IIF Expression我认为您使用的是SQL Server 2012或更高版本,因此您也可以使用IIF编写上述语句:

UPDATE t1
 SET t1.RptGChng = IIF(t1.[Status] = 'Green' AND  t1.[Status] <> t2.[Status], 1 , t1.RptGChng) 
    ,t1.RptAChng = IIF(t1.[Status] = 'Amber' AND  t1.[Status] <> t2.[Status], 1 , t1.RptAChng)
    ,t1.RptRChng = IIF(t1.[Status] = 'RED'   AND  t1.[Status] <> t2.[Status], 1 , t1.RptRChng)
FROM Table1 t1 
INNER JOIN Table2 t2  ON t1.[id]= t2.[id]