SQL update rows in column using CASE statement

给你一囗甜甜゛ 提交于 2019-12-23 09:52:03

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/14388064/sql-update-rows-in-column-using-case-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!