在 sql 中使用条件更新语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6097815/
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 10:42:02  来源:igfitidea点击:

using a conditional update statement in sql

sqlsql-server

提问by Saravanan

I would like to have an update statement like this

我想要这样的更新语句

 SELECT * from Employee
 WHERE age = CASE 
 WHEN (age < 20) THEN age=15
 WHEN (age > 20) THEN age= 20

Is this not possible in SQL Server / MySQL. I do not want to use the stored procedures or other things.

这在 SQL Server / MySQL 中是不可能的。我不想使用存储过程或其他东西。

Suggest me a suitable way around this problem

建议我解决这个问题的合适方法

回答by JNK

I think what you want is:

我想你想要的是:

UPDATE EMPLOYEE
SET age =
CASE WHEN AGE < 20 THEN 15
ELSE 20 END

回答by EBarr

You can use a case statement in an update as follows...

您可以在更新中使用 case 语句,如下所示...

UPDATE Employee 
SET Age = CASE WHEN (age < 20) THEN 15
              ELSE 20 END