Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql where子句和els中的Case语句不起任何作用_Sql - Fatal编程技术网

Sql where子句和els中的Case语句不起任何作用

Sql where子句和els中的Case语句不起任何作用,sql,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 此查询适用于我,但不适用于@Stat

请检查下面的查询

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     
如果@Status='0'
从主表中选择id、代码,其中
('07/31/2012'介于开始日期和结束日期之间)和状态=@Status
如果@code“0”
从主表中选择id、代码,其中
('07/31/2012'介于开始日期和结束日期之间)和状态=@Status和代码=@code
其他的
从主表中选择id、代码,其中
('07/31/2012'从开始日期到结束日期)
如果@code“0”
从主表中选择id、代码,其中
('07/31/2012'介于开始日期和结束日期之间)和状态=@Status和代码=@code

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

您可以通过稍微重新措辞来简化查询:

select  id,code 
from    MasterTable 
where   '07/31/2012' between  StartDate and EndDate)
        and (@status <> '0' or Status = @status)
选择id,code
来自MasterTable
其中“2012年7月31日”介于开始日期和结束日期之间)
和(@status“0”或status=@status)

@Andomar,如果不止一个where标准,请检查我的更新问题。您可以添加许多行,如
(@a'0'或col1=@a)和(@b'0'或col2=@b)和…
@Andomar您能用这个特定的更新问题更新您的答案吗?我也有同样的问题。我只理解单个条件,但在多个(或嵌套)条件中会混淆。@Andomar是否有
WHERE
conditions和嵌套条件的官方文档(链接)?哪个SQL?SQL Server、MySQL等。。