Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.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:声明多个变量,这些变量不会同时使用_Sql_Sql Server_Dynamic Sql - Fatal编程技术网

SQL:声明多个变量,这些变量不会同时使用

SQL:声明多个变量,这些变量不会同时使用,sql,sql-server,dynamic-sql,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中有

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

 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
将被忽略。

一种方法类似于

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

一种方法是

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

当然,你也可以考虑不初始化变量(特别是int或日期到空字符串)。空字符串仍然是一个值。被什么忽略?如果它们都有价值呢?何时分配这些值?为什么要标记<代码>动态SQL ?请确认。也可以考虑不初始化变量(特别是int或日期为空字符串)。空字符串仍然是一个值。被什么忽略?如果它们都有价值呢?何时分配这些值?为什么要标记动态sql?谢谢!这帮了大忙!非常感谢。这帮了大忙!