且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL使用CASE语句更新列中的行

更新时间:2023-02-05 18:42:32

您可以在UPDATE语句中使用联接.

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

注意:

  • 您还可以使用子查询,但这会慢很多(n阶的平方而不是n阶).对于少数用户而言,这没关系.

  • 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.

我没有没有测试,所以我在上面的代码中可能有错别字/错误.

基于关于此操作不可行的疯狂评论,我实施了一个小提琴.

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

享受它的工作:

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