Skip to content
Advertisement

How to do an UPDATE with several SELECT in value to update in MSSQL

I’m trying to update a value which is the result of 2 SELECT

UPDATE table2
    SET  value = (SELECT value FROM table1 WHERE table1.id = (SELECT value2 FROM table3 WHERE table3 = Value3 )),
    ValueDate = GETUTCDATE()
    WHERE table2.createdby= USER1

I checked that the following request give me a column of several value :

select value from table1 where table1.id = (select value2 from table3 where table3 = Value3

When I tried the update MSSQL retruned me this error message :

Msg 512, Niveau 16, État 1, Ligne 1
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.

I tried subquery with IN after ‘value’ is not working

Advertisement

Answer

The error you cite means that your subquery returns multiple values:

   SELECT value FROM table1 WHERE table1.id = (SELECT value2 FROM table3 WHERE table3 = Value3 )

This is aproblem because you are comparing the dataset that comes from the above query to a single (scalar) value, and those two things cannot equate.

As mentioned by some comments, a better way to do UPDATEs involving multiple tables is to use a FROM clause like in your SELECT queries directly in the UPDATE:

UPDATE table2
    SET 
        table2.value = table1.value,
        ValueDate = GETUTCDATE()
    FROM table2
        JOIN table3 ON table3.value3 = table2.value3 -- (??? condition here is unclear)
        JOIN table1 ON table1.ID = table3.value2
    WHERE table2.createdby= USER1

Note that the above, if there are multiple matches for a single row of table2, will use the last value in the recordset for the value.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement