Build dynamic query(dynamic operator) in SSRS using a complex query

后端 未结 1 1104
孤城傲影
孤城傲影 2021-01-14 09:27

I would like to build a dynamic query for a specific report using some parameters (dynamic operators).

How can I add dynamic parameters without writing/editing the e

相关标签:
1条回答
  • 2021-01-14 10:29

    There are a few approaches here.

    I created some sample data to test against:

    create table ReportTest
    (id int, value int, testDate date)
    
    insert into ReportTest
    values
    (1, 100, '01-jan-2013'),
    (2, 200, '01-feb-2013'),
    (3, 300, '01-mar-2013'),
    (4, 400, '01-apr-2013')
    

    I've also added three parameters:

    • Date
    • Operator (available values are < and > for my report)
    • OperatorValue (integer)

    Expression-based

    First question is why did your query work in the editor but not as an expression?

    You can reference parameters in the editor and SSRS will transform these as required, if possible. This works fine for the date parameters as you've seen, but SSRS won't know what to do with the Operator parameter.

    When using an expression-based DataSet, SSRS will apply no transformation at all - it will just try and put a string together then throw this at the Data Source and hope it works. This means that the expression has to apply any formatting/updating itself to create an appropriate query.

    The following worked for me with the above table/parameters:

    ="select * from ReportTest where testDate > '"
      & CDate(Parameters!Date.Value).ToString()
      & "'"
      & " and value " & Parameters!Operator.Value & " " & CStr(Parameters!OperatorValue.Value)
    

    So when applied this is turned into a usable query that works as required.

    You do get a warning when applying this:

    enter image description here

    This makes sense as SSRS can't tell what will be received before actually running the dynamic query.

    As such you'll need to set up the columns before moving to an expression-based query.

    Editor-based

    It's difficult to apply an operator-type parameter without dynamic SQL, but you can do something similar with a CASE statement. This works for me through the query editor:

    select *
    from ReportTest
    where testDate > @Date
      and ((@Operator = '>' and value > @OperatorValue)
        or (@Operator = '<' and value < @OperatorValue))
    

    Depending on how you look at it, the query is slightly more complex, but it does avoid having to use an expression-based query.

    Both of the above examples worked on my simple table:

    enter image description here

    Both approaches are still viable as you add more complexity, e.g. more tables, aggregation, it will still be the same principle.

    0 讨论(0)
提交回复
热议问题