首页 > 解决方案 > 基于行数据的更新查询中的case语句

问题描述

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

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 中创建此存储过程。

标签: c#sqlsql-server

解决方案


情况可能是

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 

推荐阅读