【问题标题】:Updating a table with multiple values from a select statement where the date matches从日期匹配的选择语句中更新具有多个值的表
【发布时间】:2010-08-11 13:39:34
【问题描述】:

我在更新表格时遇到问题,我确定它非常简单,但我在这里转圈圈。

我要更新的表'table1'数据格式如下:

[Month]                    Figure
----------------------------------
2010-05-01 00:00:00.000 1.0000
2010-06-01 00:00:00.000 1.0000
2010-07-01 00:00:00.000 1.0000
2010-08-01 00:00:00.000 1.0000

包含更新数据的表“data1”的格式如下:

[Month]                    Figure
----------------------------------
2010-05-01 00:00:00.000 0.7212
2010-08-01 00:00:00.000 1.2351

我使用的SQL和错误信息如下。

UPDATE t1
SET t1.figure = (SELECT figure from data1)
FROM table1 t1 JOIN data1 d1
ON (t1.[month] = d1.[month])


Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

我需要一个while循环来遍历每一行吗?

我希望最终结果如下:

[Month]                    Figure
----------------------------------
2010-05-01 00:00:00.000 0.7212
2010-06-01 00:00:00.000 1.0000
2010-07-01 00:00:00.000 1.0000
2010-08-01 00:00:00.000 1.2351

非常感谢。

【问题讨论】:

    标签: sql sql-server join sql-update


    【解决方案1】:

    您可以为此使用UPDATE FROMsyntax。

    看看herehere的语法。

    FROM (table_source)

    指定表、视图或派生表源用于 提供更新操作的标准

    UPDATE  t1
    SET     t1.figure = data1.figure
    FROM    t1
            INNER JOIN data1 ON data1.month = t1.month
    

    【讨论】:

    【解决方案2】:
    UPDATE t1
    SET t1.figure = data1.figure 
    FROM table1 t1 JOIN data1 d1
    ON (t1.[month] = d1.[month])
    

    【讨论】:

      【解决方案3】:

      SQL Server 2008:

      MERGE INTO Table1
      USING data1 AS D1
         ON Table1.my_Month = D1.my_Month
      WHEN MATCHED 
         THEN UPDATE 
                 SET Figure = D1.Figure;
      

      SQL Server 2008 之前的版本:

      UPDATE Table1
         SET Figure = (
                       SELECT D1.Figure
                         FROM data1 AS D1
                        WHERE Table1.my_Month = D1.my_Month
                      )
       WHERE EXISTS (
                     SELECT *
                       FROM data1 AS D1
                      WHERE Table1.my_Month = D1.my_Month
                    );
      

      请注意,UPDATE..FROM 语法是专有的,当目标行与多个源行匹配时会产生不可预知的结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-19
        • 1970-01-01
        • 2014-06-23
        • 2021-04-27
        • 1970-01-01
        • 2019-06-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多