开发者

Updating a table with multiple values from a select statement where the date matches

I'm having a problem updating a table and im sure its pretty straight forward but im going round and round in circles here.

Table 'table1' data I want to update is formatted as follows:

[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

Table 'data1' that contains the updated figures is formatted as follows:

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

The SQL I'm using and the error message is as follows.

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.

Would i need a while loop to go through each row?

I wish the end result to be as follows:

[Month]                    Figure
----------------------------------
2010-05-01 00:00:00.000 0.7212
2010-06-01 00:00:00.00开发者_JS百科0 1.0000
2010-07-01 00:00:00.000 1.0000
2010-08-01 00:00:00.000 1.2351

Much appreciated.


You can use the UPDATE FROMsyntax for this.

Have a look at the syntax here and here.

FROM (table_source)

Specifies that a table, view, or derived table source is used to provide the criteria for the update operation

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


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


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
              );

Note the UPDATE..FROM syntax is proprietary and can yield unpredictable results when a target row matches more than one source row.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜