Updating a table with multiple values ​​from a select statement that matches a date

I had a problem updating the table, and I'm sure that it is pretty straight forward, but I'm spinning around here.

The table "table1" the data that 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

The table 'data1', which contains the updated data, 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.

Do I need a while loop to go through each line?

I want 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

Great importance.

+3
source share
3 answers

UPDATE FROM.

.

FROM (table_source)

, ,

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

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 that the syntax UPDATE..FROMis proprietary and may produce unpredictable results when the target line matches more than one source line.

0
source

Source: https://habr.com/ru/post/1759133/


All Articles