Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 case statement

Author  Topic 

tpiazza55
Posting Yak Master

162 Posts

Posted - 2012-01-16 : 19:23:38
i have a table

tranid detailkey detailvalue
1 key1 value1
1 key2 value2

on a update statement i only want to update 1 detailvalue with a case statement

CASE
WHEN detailkey = 'key1' THEN newvalue1
end

this updates key1 value but makes key2 value null

how do you use a case to update the one you want and not touch the other values?

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-01-16 : 19:31:54
Use a where clause like this:
UPDATE yourTable SET
detailValue = newValue
WHERE
detailkey = 'key1';
If you must use a case expression, do it like this, where you explicitly tell SQL to leave detailValue alone (i.e., set it to itself) if detailkey is not key1
UPDATE yourTable SET
detailValue =
CASE
WHEN detailkey = 'key1' THEN newvalue1
ELSE detailValue
END
Go to Top of Page

tpiazza55
Posting Yak Master

162 Posts

Posted - 2012-01-17 : 12:02:35
thanks
Go to Top of Page
   

- Advertisement -