2016-01-19 59 views
0

我有兩個表,並希望在SQL Server 2008中更新表T:SQL服務器 - 如何更新多列/條件,而忽略某些列WHERE語句

表寬:

+--------+----+------+------+------+ 
| 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:如何忽略更新上的cols在寒冷和F數據C數據(所以基本上,忽略任何數據,其中冷= C和cols = F)

表筆與其他列:

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

什麼是'PROJSTARTDATE的數據類型'。 –

+0

datetime,所有的字段都是日期時間,除了ID列 –

+0

然後你永遠不能在datetime字段中存儲**文本**'NULL' –

回答

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 .... 

你沒有看到很多的更新outer joins雖然...

+0

需要更正.if例如w.PROJSTARTDATE ='NULL'then getdate()。second correction.getdate()會拋出錯誤,因爲數據類型不是datetime.it必須是varchar – KumarHarsh

+0

@KumarHarsh是的,上面的查詢在將日期從字符串錯誤。這可以通過將列轉換爲varchar來解決嗎? –

+0

@AlkippeNikephoros,yup convert getdate()to varchar – KumarHarsh

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()) 
....