SQL Server - 如何在WHERE语句

时间:2016-01-19 03:40:26

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

我有两个表,想要更新SQL Server 2008中的表t:

表格w:

+--------+----+------+------+------+
| DataID | AFD|  PSD |  PFD | ASD  |    
+--------+----+------+------+------+
|      1 | B  | E    | A    |      |  
|      2 | I  |      | B    |  W   |      
|      3 |    |      | Y    |  D   |   
|      4 |    | Q    |      |  T   |     
|      5 | T  | E    | D    |  T   | 
+--------+----+------+------+------+

表t:

+--------+----+------+------+------+
| DataID | AFD|  PSD |  PFD | ASD  |    
+--------+----+------+------+------+
|      1 | A  | E    |      |  Z   |  
|      2 | B  | F    | Y    |      |      
|      3 | C  | G    | G    |  T   |   
|      4 | B  | E    |      |      |     
|      5 | T  | G    | Y    |  Z   | 
+--------+----+------+------+------+

问题/尝试:如何更新表t检查多个条件?

注意:NULL是文本而不是空列。

update t
SET t.ACTFINISHDATE = GETDATE()
,t.PROJSTARTDATE = 
(CASE 2
WHEN t.PROJSTARTDATE = 'NULL' THEN t.PROJSTARTDATE = w.PROJSTARTDATE
WHEN w.PROJSTARTDATE = 'NULL' THEN GETDATE()
ELSE GETDATE()
END)
,t.PROJFINISHDATE =
(CASE 3
WHEN t.PROJFINISHDATE = 'NULL' THEN t.PROJFINISHDATE = w.PROJFINISHDATE
WHEN w.PROJFINISHDATE = 'NULL' THEN GETDATE()
ELSE GETDATE()
END)
,t.ACTSTARTDATE =
(CASE 3
WHEN t.ACTSTARTDATE = 'NULL' THEN t.ACTSTARTDATE = w.ACTSTARTDATE
WHEN w.ACTSTARTDATE = 'NULL' THEN GETDATE()
ELSE GETDATE()
END)

FROM w
  JOIN t ON w.DataID = t.DataID
WHERE   ( ( cold IN ( 'A', 'B' ) 
       AND cols IN ( 'E', 'F' ) ) 
      OR ( cold = 'C' 
           AND cols = 'G' ) ) 

问题2:如何忽略col中的C数据和col中的F数据的更新(所以基本上忽略Cold = C和ColS = F的任何数据)

表t以及其他列:

+--------+-----+-------+
| DataID | Cold|  ColS |    
+--------+-----+-------+
|      1 | A   | E     | 
|      2 | B   | G     |      
|      3 | A   | G     |  
|      4 | B   | E     |   
|      5 | C   | F     |
|      6 | C   | F     |
+--------+-----+-------+

2 个答案:

答案 0 :(得分:1)

假设您的join正在运行,那么您的case语句应更改如下:

update t
set t.ACTFINISHDATE = GETDATE(),
    t.PROJSTARTDATE = 
        CASE WHEN t.PROJSTARTDATE = 'NULL' THEN w.PROJSTARTDATE
        ELSE GETDATE()
        END,
    t.PROJFINISHDATE =
        CASE WHEN t.PROJFINISHDATE = 'NULL' THEN w.PROJFINISHDATE
        ELSE GETDATE()
        END,
    t.ACTSTARTDATE =
        CASE WHEN t.ACTSTARTDATE = 'NULL' THEN w.ACTSTARTDATE
        ELSE GETDATE()
        END
FROM w
    LEFT JOIN T ON..
WHERE ....

尽管...... {/ p>,但您看不到outer joins的许多更新

答案 1 :(得分:1)

假设值为NULL而不是'NULL',例如,您可以这样做:

update t
SET t.ACTFINISHDATE  = GETDATE()
   ,t.PROJSTARTDATE  = COALESCE(t.PROJSTARTDATE,  w.PROJSTARTDATE,  GETDATE())
   ,t.PROJFINISHDATE = COALESCE(t.PROJFINISHDATE, w.PROJFINISHDATE, GETDATE())
   ,t.ACTSTARTDATE   = COALESCE(t.ACTSTARTDATE,   w.ACTSTARTDATE,   GETDATE())
 ....