使用日期匹配的select语句中的多个值更新表

时间:2010-08-11 13:39:35

标签: sql sql-server join sql-update

我在更新桌子时遇到了问题,我确信它非常简单,但我会在这里绕圈转。

我要更新的表'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

非常感谢。

3 个答案:

答案 0 :(得分:5)

您可以使用UPDATE FROM语法。

查看语法herehere

  

FROM(table_source)

     

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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;

Pre-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语法是专有的,当目标行与多个源行匹配时,会产生不可预测的结果。