I want to update a column only if a condition is met. So for the column "Type", I want to change its value to "MongoDB" only if its current value isn't "MongoDB" This is what I'm using:
UPDATE Report
SET Type =
CASE
WHEN Type <> 'MongoDB' THEN 'MongoDB'
ELSE Type
END
WHERE Id = x
The problem is: Even when the Type is "MongoDB" I still see
(1 row(s) affected)
in my SQL result. The whole point of this exercise was to reduce db operations when no needed. Why is it still modifying the record when the condition is not met?
Thanks.
To do a conditional update depending on whether the current value of a column matches the condition, you can add a WHERE clause which specifies this. The database will first find rows which match the WHERE clause and then only perform updates on those rows.
UPDATE syntax:UPDATE table_name SET column_name = value WHERE condition; To perform the above function, we can set the column name to be equal to the data present in the other table, and in the condition of the WHERE clause, we can match the ID. we can use the following command to create a database called geeks.
UPDATE statements with a FROM clause are often used to update information in a table based on a table-valued parameter (TVP), or to update columns in a table in an AFTER trigger. For the scenario of update based on a TVP, see Implementing MERGE Functionality in a Natively Compiled Stored Procedure.
We can modify one or multiple records (rows) in a table using UPDATE statement. If you do not use WHERE clause in UPDATE statement, all the records in the table will be updated.
Why not simplify it like this?
UPDATE Report
SET Type = 'MongoDB'
WHERE Id = x AND Type <> 'MongoDB'
But to answer your question you are still setting a records value even though its to the existing value. The record also comes back in the where clause so you will always have 1 row affected regardless of your CASE statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With