2011-05-27 102 views
1

我有一些這樣的代碼:SQL語法幫助 - 更新

Update table_name 
set 
[column] = case when d.data is null, then null else d.columnname end. 

from... 
etc 

我的問題是,我該如何建立一個函數,其中的「其他d.columnname」是總結幾列的聯接。

難道是這樣的:

...then null else sum(d.column1 + rf.column2 + rwf.column3) as tempcolumn end, 

...then null else (d.column1 + rf.column2 + rwf.column3) end, 

什麼是做在這組形勢柱和正確的方法是什麼?

+0

你有沒有嘗試過任何一個? – JNK 2011-05-27 15:24:54

+0

是的,一個工作沒有錯誤,但它說0行更新,我100%肯定這應該更新一行,所以我認爲我有一些不好的語法 – 2011-05-27 15:26:10

回答

2

你可以簡單地做:

update MyTable 
set column = 
    case 
     when d.data is not null 
     then d.column1 + rf.column2 + rwf.column3 
    end 
from ... 

CASE將默認返回NULL當沒有比賽。

0

像這樣的東西應該工作:

UPDATE table_name 
    SET [column] = CASE WHEN d.data IS NULL 
          THEN null 
          ELSE (d.column1 + rf.column2 + rwf.column3) 
        END 
    FROM table_name 
     INNER JOIN other_table1 d ON ... 
     INNER JOIN other_table2 rf ON ... 
     INNER JOIN other_table3 rwf ON ... 

當然,在上面的查詢你必須把在內蒙古表之間的正確關係JOIN - ON子句