SQL 更新一列中的多个值

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

Updating multiple values within the one column

sqlsql-update

提问by Will

I have the following SQL which I have written to update a tables values:

我编写了以下 SQL 来更新表值:

Update Table
SET S_Type = 'Versus'
Where S_Type = 'REGULAR'
SET S_Type = 'Free'
Where S_Type = 'CASH';

My SQL is rather rusty, and my colleague told me something was up with it but didn't tell me what!

我的 SQL 相当生疏,我的同事告诉我它出了点问题,但没有告诉我是什么!

The only thing that comes to mind is I have not referred to the Table.Column in the set and Where code.

唯一想到的是我没有在 set 和 Where 代码中提到 Table.Column。

Is there any issue updating a column as such? What is the best practice when updating a column for multiple values?

这样更新列有什么问题吗?为多个值更新列时的最佳做法是什么?

Cheers

干杯

回答by jainvikram444

Here , we are using case statement and find result like as where clause :

在这里,我们使用 case 语句并找到类似 where 子句的结果:

update tablename
set S_Type = (case S_Type  when 'REGULAR' then 'Versus'
                           when 'CASH' then 'free' 
                           else s_type 
                           end)

回答by podiluska

Update YourTable
set S_Type = 
    case S_Type 
        when 'REGULAR' then 'Versus'
        when 'CASH' then 'free' 
        else s_type 
        end

回答by Myles J

Are you using SQL Server? If you are using 2012 you can now write simplified conditional update statements using the new CHOOSE or IIF features e.g:

你在使用 SQL Server 吗?如果您使用的是 2012,您现在可以使用新的 CHOOSE 或 IIF 功能编写简化的条件更新语句,例如:

Update YourTable
set S_Type = IIF(S_Type = 'REGULAR', 'Versus', 'free') 

My two pennies worth.

我的两便士值。