SQL语法帮助 - 更新

时间:2011-05-27 15:22:03

标签: sql sql-server syntax

我有一些像这样的代码:

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

from...
etc

我的问题是,我如何设置一个函数,其中'else 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,

在此设定情况下执行列总和的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

您可以这样做:

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

CASE默认情况下会在没有匹配时返回NULL

答案 1 :(得分: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 ...

当然,在上面的查询中,你必须在INNER JOIN - ON子句中的表之间放入正确的关系