【问题标题】:SQL Syntax Help - UpdateSQL 语法帮助 - 更新
【发布时间】:2011-05-27 15:22:02
【问题描述】:

我有一些这样的代码:

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,

在这种情况下进行列求和的正确方法是什么?

【问题讨论】:

  • 是的,一个工作没有错误,但它说 0 行更新,我 100% 肯定这应该更新一行,所以我认为我有一些错误的语法

标签: sql sql-server syntax


【解决方案1】:

你可以这样做:

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

CASE在没有匹配时默认返回NULL

【讨论】:

    【解决方案2】:

    这样的事情应该可以工作:

    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 子句中输入正确的表之间的关系

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 2013-08-21
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      相关资源
      最近更新 更多