【问题标题】:Conditional parameters in SSRSSSRS 中的条件参数
【发布时间】:2016-12-13 11:01:38
【问题描述】:

是否有更有效的方法来为 SSRS 报告创建 SQL 查询,根据参数值,它会返回针对日期字段过滤的记录:1 = 没有结束日期的所有行 2 = 结束日期为 3 的所有行= 所有行,无论参数值如何。我提出了以下查询,但使用布尔值,它需要一个 or 语句为每个条件重复(我必须添加更多条件!

我遇到的另一个问题/问题是在使用 IF 或 CASE 时 - 我收到一条错误消息,指出 sclar 变量无效。当我声明并使用默认值设置参数时,它可以工作。但不确定 CASE/IF 在这种情况下是否理想?谢谢。

SELECT table.field_seq_no, table.field_end_dt, MyTable2.area_off
FROM table 
INNER JOIN MyTable2 
  ON table.comp_id = MyTable2.comp_id 
  AND table.prty_ref = MyTable2.prty_id
WHERE ((table.field_end_dt IS NULL)
  AND (@Parameter = 1) 
  AND (MyTable2.area_off IN (@area)) 
OR ((table.field_end_dt IS NOT NULL) 
  AND (@Parameter = 2) 
  AND (MyTable2.area_off IN (@area)) 
OR ((@Parameter = 3) AND (MyTable2.area_off IN (@area))

【问题讨论】:

  • 在 where 子句中使用 case 表达式通常是个坏主意。 (难以优化等)
  • 就个人而言,我会将其移至 SSRS 中的表达式并使用 switch(Parameters!Parameter1.Value = 1, <SQL1>, Parameters!Parameter1.Value = 2, <SQL2>, Parameters!Parameter1.Value = 3, <SQL3>)

标签: sql sql-server reporting-services parameters


【解决方案1】:

如果你稍微改变你的查询,实际上没有重复的代码,忽略对@Parameter值的检查:

select t1.field_seq_no
      ,t1.field_end_dt
      ,t2.area_off

from table t1
  inner join MyTable2 t2
    on t1.comp_id = t2.comp_id 
      and t1.prty_ref = t2.prty_id
      and t2.area_off IN (@area)    -- This part is consistent so doesn't need to be repeated.

where (@Parameter = 1
       and t1.field_end_dt is null
      )
  or (@Parameter = 2
      and t1.field_end_dt is not null
     )
  or @Parameter = 3;

当然,如果你觉得过滤语句不应该放在JOIN 子句中,你可以把它放在你的WHERE 中加上一些额外的括号:

select t1.field_seq_no
      ,t1.field_end_dt
      ,t2.area_off

from table t1
  inner join MyTable2 t2
    on t1.comp_id = t2.comp_id 
      and t1.prty_ref = t2.prty_id

where t2.area_off IN (@area)    -- This part is consistent so doesn't need to be repeated.
  and (
         (@Parameter = 1
           and t1.field_end_dt is null
         )
      or (@Parameter = 2
          and t1.field_end_dt is not null
         )
      or @Parameter = 3
      );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多