SQL:声明多个不会同时使用的变量

时间:2018-10-26 14:37:20

标签: sql sql-server dynamic-sql

我正在编写一个查询,该查询需要设置多个变量,但不能同时使用所有变量。看起来像这样。

 Declare @SuveryID as Int 
 Declare @StateAbbrev as Varchar
 Declare @InvStart as Date
 Declare @InvEnd as Date
 Set @SuveryID = ''
 Set @StateAbbrev = ''
 Set @InvStart = ''
 Set @InvEnd = ''

我想要执行的操作是,每当调查ID中包含值时,其他值都会被忽略。只要@StateAbbrev@InvStart@InvEnd都有一个值,@SurveryID就会被忽略。

1 个答案:

答案 0 :(得分:3)

一种方式就是...

if @SuveryID  is null
begin
   select *
   from YourTable
   where <all your other variables>
end
else
begin
   select *
   from YourTable
   where Column = @SuveryID  
end

另一种方法是在NULL时将变量设置为@SuveryID is not null,然后使用全部捕获查询。这些称为Kitchen Sink查询,Aaron Bertrand的文章值得一读。

if @SuveryID  is not null
begin
   set @StateAbbrev  = null
   set @InvStart  = null
   <set all other variables to null>
end

select *
from YourTable
where (Column = @SuveryID or @SuveryID is null)
and   (Col2 = @StateAbbrev or @StateAbbrev  is null)
and   <continue for all variables>