如何在不查询查询的情况下忽略查询中的参数

时间:2016-01-15 11:38:18

标签: sql-server tsql reporting-services

我从SSRS报告的数据集中复制了一个查询,例如3个参数。在实际情况中,我有很多约30个参数。我想在SSMS中测试此查询并使用我自己的值处理参数。但我想填写查询一个参数 - @ par1,其他必须具有所有值。

drop table testtable;
create table testtable(param1 int,param2 int,param3 int)
insert into testtable values 
(1,10,20),(2,11,21),(3,12,22);

--added parametrs to help query work
declare @par1 int;
declare @par2 int;
declare @par3 int;
set @par1=1;
set @par2= ? --what i need to put here to have only @par1 condition implemented in query
set @par3= ? --what i need to put here to have only @par1 condition implemented in query

-- Dataset Copyed from SSRS Report. And I dont want to delete anything from here, because query is complex in real situation.
select *
from testtable
where 
param1=@par1 and param2=@par2 and param3=@par3

4 个答案:

答案 0 :(得分:3)

我想这对你有用

select *
from testtable
where (param1=@par1 or @par1 is null) 
  and (param2=@par2 or @par2 is null) 
  and (param3=@par3 or @par3 is null)

答案 1 :(得分:2)

似乎没有办法做你想做的事......

答案 2 :(得分:0)

如果您不想忽略这些参数Null,请尝试以下操作:

select * from testtable
where 
( ( param1 = @par1 ) or ( param1 is null) )
and ( ( param2 = @par2 ) or ( param2 is null) )
and ( ( param3 = @par3 ) or ( param3 is null) )

<强>更新

刚看到您不想更改查询。所以这不是解决方案。我无法想出一些东西。

答案 3 :(得分:0)

这应该有效:

select *
from testtable
where  ISNULL(@par1,0) IN (param1,0)
  and ISNULL(@par2,0) IN (param2,0)
  and ISNULL(@par3,0) IN (param3,0)