Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.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 Server根据可选参数添加where子句的条件_Sql_Sql Server_Stored Procedures - Fatal编程技术网

如何使用SQL Server根据可选参数添加where子句的条件

如何使用SQL Server根据可选参数添加where子句的条件,sql,sql-server,stored-procedures,Sql,Sql Server,Stored Procedures,我的存储过程中有一个“可选”参数,如果我的参数有某个值,那么我需要在现有查询中添加一个条件where语句 我不想有一个单独的语句,基本上在这里我想做什么,但我不确定是否可能与SQL Server @myRole varchar='' -- here's optional parameter SELECT blah blah FROM myTable WHERE <I_have_here_existing_conditions> AND h

我的存储过程中有一个“可选”参数,如果我的参数有某个值,那么我需要在现有查询中添加一个条件where语句

我不想有一个单独的语句,基本上在这里我想做什么,但我不确定是否可能与SQL Server

@myRole varchar=''  -- here's optional parameter

SELECT blah blah 
FROM myTable
WHERE 
     <I_have_here_existing_conditions>
     AND
         here I want to add another condition based on my @myRole parameter-something like
      if myRole='Employee' then add to where condition: myStatus = 'Y'*
这里有一个方法:

select * 
from yourtable
where
 [other conditions]
and (@myRole <> 'Employee' OR  myStatus = 'Y')
使用这样的大小写表达式:

where <other conditions>
     and case when @myRole = 'Employee' then myStatus else 'Y' end = 'Y'

假设@myrole为null或定义的值

select *
from Table
where ...
and (@myrole is null or (myStatus='Y' and @myrole='Employee'))

如果它总是定义为,那么只需使用@myrole=或

就可以将@myrole设置为NULL,或者如果不使用它,它是否总是空字符串?我知道你不需要额外的声明,但它可能会更有效。如果希望避免重复,可以使用动态SQL