Search code examples
javajasper-reports

How to pass optional parameter to the report?


I am creating JR report with embedded sql query by iReport 4.5.0.

I already added parameter in Query. But I will want to give flexibility so that user can pass parameter or can not pass parameter so that same report can work with my web application.

Can anyone tell me how can make my report that much flexible so that user can or cant pass parameters.

I modified the queryString like this:

SELECT columnA, ColumnB FROM Table WHERE Table."columnA" = $P!{}

But iReport failed to generate report.


Solution

  • I usually follow this pattern: Define $P{MyParam} as you did. Then add $P{MyParam_SQL} with a default value like this:

    $P{MyParam} == null ? "1=1" : "columnA = '" + $P{MyParam} + "'"
    

    And the SQL in the report is like this:

    SELECT columnA, ColumnB 
    FROM table 
    WHERE 
      some_filters
      AND $P!{MyParam_SQL}
      AND some_other_stuff
    

    It's not fundamentally different from the other two suggested answers. But I find it easy to understand and maintain like this.