SQL 在更新查询中使用 case 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2227843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 05:19:33  来源:igfitidea点击:

Using case statement in update query

sqlsql-serversql-server-2005

提问by Prabhu

Is it possible to use case statement within an update query? I need to do something like this: If person name starts with 'S' then append '1', else append '2'.

是否可以在更新查询中使用 case 语句?我需要做这样的事情:如果人名以“S”开头,则附加“1”,否则附加“2”。

I tried this in sql server and it didn't work

我在 sql server 中试过这个,但没有用

UPDATE PERSON
CASE
WHEN NAME LIKE 'S%' THEN SET NAME = NAME + '1'
ELSE SET NAME = NAME + '2'
END

回答by AdaTheDev

Just to add a slightly different variant that I tend to prefer (down to personal preference).

只是添加一个我倾向于喜欢的略有不同的变体(根据个人喜好)。

UPDATE Person
SET Name = Name + CASE WHEN Name LIKE 'S%' THEN '1' ELSE '2' END

I like this because it saves repeating the "Name +" bit for each condition - in this case it's nothing major, but in other scenarios with more conditions it can be overly repetitive

我喜欢这个,因为它可以为每个条件节省重复“名称+”位 - 在这种情况下,这没什么大不了的,但在其他条件更多的情况下,它可能会过度重复

回答by Heinzi

CASE WHENreturns an expression, not a statement. You can use it like this:

CASE WHEN返回一个表达式,而不是一个语句。你可以这样使用它:

UPDATE PERSON
SET NAME = CASE WHEN NAME LIKE 'S%' THEN NAME + '1'
                                    ELSE NAME + '2'
           END

回答by Antony Koch

It will be:

这将是:

update person
set name = case when name left(name,1) = 'S' then name + '1' else name + '2' end