UPDATE MyTable SET Status = (SELECT CASE WHEN COUNT(*) > 0
THEN 0
ELSE 1
END
FROM MyTable
WHERE Status = 1 )
WHERE RowNumber BETWEEN 1 AND 5
ORDER BY RowNumber
What I want to do is there will be only one row in MyTable with Status = 1. While I update RowNumber 1 to 5, if there has been an existing record with Status = 1, those RowNumber 1 to 5 will be updated with 0. Otherwise, only RowNumber 1 will be updated to 0 and RowNumber 2 to 5 will be set 0.
But aforementioned query is not working. I guess sub-query is run before the whole query and the result from the sub-query is static which means not giving new result as one record after another is being updated.
With this query, if there is no row in the table with Status = 1 then all RowNumber 1 to 5 are updated with Status = 1. This is not what I am expecting.
Not sure if I understand fully what you're after - but it sounds like you need to add a nested case statement in the else clause of your original case. See the code below:
UPDATE MyTable SET Status = (SELECT CASE WHEN COUNT(*) > 0
THEN 0
ELSE CASE WHEN RowNumber = 1 THEN 1
ELSE 0 END
END
FROM MyTable
WHERE Status = 1 )
WHERE RowNumber BETWEEN 1 AND 5
ORDER BY RowNumber
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.