In SQL Server and MySQL, you can use an UPDATE statement with a CASE expression directly in the SET clause to conditionally update values based on certain conditions. Here’s how you can structure the query:
UPDATE Employee SET age = CASE
WHEN age < 20 THEN 15
WHEN age > 20 THEN 20
ELSE age -- Keep the current age if it's exactly 20
END WHERE age <> 20; --Optional: Only update rows where age is not already 20
Explanation:
- CASE expression in SET: The CASE checks each row's age and applies the appropriate value.
- WHERE clause: Using WHERE age <> 20 (optional) prevents unnecessary updates for rows where age is already 20.
This query will update age to 15 if it’s less than 20, to 20 if it’s greater than 20, and leave age unchanged if it’s exactly 20.
This method avoids the need for stored procedures and is compatible with both SQL Server and MySQL.