【问题标题】:How to ignore parametr in query without chaging query如何在不更改查询的情况下忽略查询中的参数
【发布时间】:2016-01-15 11:38:17
【问题描述】:

我有一个从 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

【问题讨论】:

  • NULL时是否要忽略参数
  • 如果参数为空。我不想忽视它。在这种情况下将是 Where @par = null
  • 我不认为你可以做你正在寻找的东西。我认为最好的选择是修改查询。此外,如果您可以这样做,并且您对查询没有很好的理解,您可能会引入错误。
  • 每次更改大查询来测试它都不是很舒服。我想找到更简单的解决方案。
  • 在声明参数时必须设置默认值。

标签: sql-server tsql reporting-services


【解决方案1】:

我想这对你有用

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

【讨论】:

  • 您修改了查询,但我不想这样做。因为在实际情况下,参数不仅位于 where 条件下。它们存在于连接、选择字段等中。
【解决方案2】:

似乎没有办法为所欲为……

【讨论】:

    【解决方案3】:

    如果你不想忽略参数,如果它们是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) )
    

    更新

    刚刚看到您不想更改查询。所以这不是一个解决方案。我想不出什么。

    【讨论】:

      【解决方案4】:

      这应该可行:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-28
        • 2019-08-28
        • 2018-06-27
        • 2021-05-27
        • 1970-01-01
        • 2015-05-13
        • 2015-03-28
        相关资源
        最近更新 更多