I’m trying to update one column in a subset of a table but I can’t figure out how to do it in a clean and efficient manner.
Consider the following:
// MyTable
id name flag
0 Steve 0
1 Bob 0
...
10500 Rick 0
I want to change flag to 1 but only for some of the cases. I tried to use
UPDATE MyTable
SET flag = 1
WHERE id <= 500
But obviously that does not work because the subquery returns more than one value. Technically, I could do it like this:
UPDATE MyTable SET flag = 1 WHERE id = 0
UPDATE MyTable SET flag = 1 WHERE id = 1
...
UPDATE MyTable SET flag = 1 WHERE id = 500
But who wants to do it like that? 🙂 Is there a better way for me to format this query and only update those which match an inequality?
EDIT
To clarify exactly what’s going on: when I say ‘some of these cases’ I only mean those which match the inequality, in this case id <= 500
When I run UPDATE MyTable SET flag = 1 WHERE id <= 500 I get the following error:
Subquery returned more than 1 value.
This is not permitted when the subquery follows =, !=, <, <= , >, >=
or when the subquery is used as an expression.
SInce your query does not have a subquery, I would suspect that you have a poorly wrtten trigger on the table that expects only one record at a time to be updated. This needs to be fixed as no trigger should ever be written on this assumption. Triggers in SQL Server need to perform only set-based operations as they work against the whole set not one row at a time.