sql - where 子句和 el 中的 case 语句不执行任何操作

标签 sql

请检查以下查询

DECLARE @status varchar(1)
DECLARE @code varchar(50)

Set @status = '0'

select id,code from MasterTable where 
('07/31/2012' between  StartDate and EndDate) and 
Case when @status = '0' and Status=@status then 1 end = 1 

此查询适用于我,但不适用于@Status=1

我需要像这样的查询

if @Status = '0'
    select id,code from MasterTable where 
   ('07/31/2012' between  StartDate and EndDate) and Status = @Status
   if @code <> '0' 
        select id,code from MasterTable where 
        ('07/31/2012' between  StartDate and EndDate) and Status = @Status and code =@code
else
     select id,code from MasterTable where 
   ('07/31/2012' between  StartDate and EndDate) 
      if @code <> '0' 
        select id,code from MasterTable where 
        ('07/31/2012' between  StartDate and EndDate) and Status = @Status and code =@code     

如何使用 case when 语句实现此目的?

最佳答案

您可以通过稍微改写来简化查询:

select  id,code 
from    MasterTable 
where   '07/31/2012' between  StartDate and EndDate)
        and (@status <> '0' or Status = @status)

关于sql - where 子句和 el 中的 case 语句不执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12280811/

相关文章:

mysql - SQL - 连接两个表

java - sql准备语句和java

javascript - 在插入数据库之前获取 UID 主键

mysql - 如何仅在 mysql 中获取最小组行?

mysql - LEFT JOIN 不会响应

php - SQL 通过条件连接其他表

sql - PostgreSQL表的实现历史

MYSQL 在两列中选择 DISTINCT 值

sqlcmd : Error: Microsoft ODBC Driver 11 for SQL Server : Login failed for user 'sa'

php - 将 CSV 文件加载到 MySQL 中返回错误