Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL update rows in column using CASE statement

I have two tables, Users and #TempTable (which is a subset of Users). I would like to update a column, IsActive, in the Users table. I would like to set IsActive = 1 if a user that is in #TempTable is also in the Users table, and set IsActive = 0 otherwise.

Getting the users from Users that are NOT in #TempTable (IsActive should be set to 0 for these users):

-- (Users \ #TempTable) U (#TempTable \ Users)
SELECT  u.UserName
FROM    Users u 
WHERE   (u.UserName) NOT IN 
    (SELECT t.[User Name] FROM #TempTable t) 
UNION ALL 
SELECT  t.[User Name] 
FROM    #TempTable t
WHERE   (t.[User Name]) NOT IN 
    (SELECT u.UserName FROM Users u)

Let's call this the ResultSet. I would appreciate some help with my UPDATE statement. What I'd like to be able to do is:

UPDATE Users
SET IsActive = (CASE WHEN User.UserName IN ResultSet THEN 0 ELSE 1 END) 

without having to write out the CASE WHEN for each User.UserName. Thanks in advance!

like image 967
Will Weld Avatar asked Jan 17 '13 21:01

Will Weld


1 Answers

You can use a join in the UPDATE statement.

UPDATE Users
SET Users.Active = CASE WHEN T.UserName is null THEN 0 ELSE 1 END 
FROM Users AS U
LEFT JOIN #TempTable AS T ON U.UserName = T.UserName

Notes :

  • You could also use a sub-query but that would be much slower (order of n squared not order of n). For a small number of users this would not matter.

  • I did not test so I could have a typo / bug in the code above.


Based on crazy comments about how this would not work I implemented a fiddle.

Enjoy it working:

http://sqlfiddle.com/#!6/25235/3

like image 109
Hogan Avatar answered Oct 10 '22 10:10

Hogan