views:

45

answers:

3

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.000 1.0000
2010-07-01 00:00:00.000 1.0000
2010-08-01 00:00:00.000 1.2351

Much appreciated.

+1  A: 
UPDATE t1
SET t1.figure = data1.figure 
FROM table1 t1 JOIN data1 d1
ON (t1.[month] = d1.[month])
Michael Pakhantsov
+2  A: 

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
Lieven
thanks, worked!
Lee_McIntosh
A: 

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.

onedaywhen