基于行数据的更新查询中的案例语句

时间:2019-03-27 08:47:06

标签: c# sql sql-server

我有一个具有以下结构的表:

ID int (primary key)
SectionName varchar(50)
Allowed bit

例如,共有5个部分:

ID   SectionName     Allowed
-----------------------------
1    Basement          1
2    First Floor       1
3    Second Floor      1
4    Third Floor       1
5    Parking           1

我有一个C#应用程序,它将使用以下填充的参数调用存储过程

@Basement = false
@First_Floor = true
@Second_Floor = true
@Third_Floor = false
@Parking = true

执行存储过程的结果后,我希望这些值看起来像

ID   SectionName     Allowed
----------------------------
1    Basement          0
2    First Floor       1
3    Second Floor      1
4    Third Floor       0
5    Parking           1

如何在Microsoft SQL Server中创建此存储过程。

3 个答案:

答案 0 :(得分:2)

情况可能是

case 
    when sectionName = 'Basement' then iif(@Basement = true, 1,0) 
    when sectionName = 'First Floor' then iif(@First_Floor = true, 1,0)         
    when sectionName = 'Second Floor' then iif(@Second_Floor = true, 1,0) 
    when sectionName = 'Third Floor' then iif(@Third_Floor = true, 1,0) 
    when sectionName = 'Parking' then iif(@Parking = true, 1,0) 
end 

您可以使用更新

update your_table  
set allowed =   case 
        when sectionName = 'Basement' then iif(@Basement = true, 1,0) 
        when sectionName = 'First Floor' then iif(@First_Floor = true, 1,0)         
        when sectionName = 'Second Floor' then iif(@Second_Floor = true, 1,0) 
        when sectionName = 'Third Floor' then iif(@Third_Floor = true, 1,0) 
        when sectionName = 'Parking' then iif(@Parking = true, 1,0) 
    end 

答案 1 :(得分:1)

您可以尝试以下操作

update table
set allowed= case when SectionName in ('Basement','Third Floor') then 0
                    else 1 end

答案 2 :(得分:1)

使用case when expression

update tablename set allowed=case when sectionName in ('Basement','Third Floor') then 0 else
1 end