I have a SQL field like so:
FIELD_A
cat
dog
bird
mole
dog
I want to UPDATE
Apparently, the SQL UPDATE
statement only allows one SET
condition at a time.
How can I write a query to accomplish the above operation all at once?
We use the SQL UPDATE syntax to modify or update existing data in a table or view in SQL Server. We can use this statement to modify a single unit of data field as well as multiple sets of data fields based on our requirements.
For instance, updating 2 different tables together in a single query/statement. This involves the use of the BEGIN TRANSACTION clause and the COMMIT clause. The individual UPDATE clauses are written in between the former ones to execute both the updates simultaneously.
There are a couple of ways to do it. INSERT INTO students (id, score1, score2) VALUES (1, 5, 8), (2, 10, 8), (3, 8, 3), (4, 10, 7) ON DUPLICATE KEY UPDATE score1 = VALUES(score1), score2 = VALUES(score2);
In SQL Server, we can join two or more tables, but we cannot update the data of multiple tables in a single UPDATE statement.
UPDATE AnonymousTable
SET Field_A = (CASE Field_A
WHEN 'dog' THEN 'pug'
WHEN 'bird' THEN 'owl'
WHEN 'cat' THEN 'angora'
ELSE Field_A END)
WHERE Field_A IN ('dog', 'bird', 'cat');
With the WHERE clause, the ELSE clause in the CASE expression is optional or redundant - but including the ELSE gives you reliability. One of the more serious mistakes is not to cover that 'none of the above' alternative and find that everything that wasn't mentioned is set to NULL.
with CASE clause you can accomplish this. here an example
http://www.java2s.com/Code/SQLServer/Select-Query/UseCASEintheUPDATEstatement.htm
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