Conditional Where clauses in JasperReports

隐身守侯 提交于 2019-11-29 07:05:49

Before you have used the $P!{} expression the JDBC-Driver does all formatting for you.

But if you use the $P!{} expression you have to format yourself.

Something like this should work:

(
$P{some.date} == null 
? 
"" 
: 
"AND some_date >'" + (new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS")).format($P{some.date}) + "'"
)

Depending on your data type you have to customize dd.MM.yyyy HH:mm:ss.SSS.

If you don't want to use the $P!{} expression you can avoid it with the solution below.

I personally don't like this way. It also may cause a bad execution plan.

If don't want to use $P!{} because you worry about sql injection. It's needless as long your parameter $P{some.date} contains a safe data type like java.lang.Date.


Create a parameter. Let's call it ${is_null_pram} and add a default expression with param class Integer:

($P{some.date} == null ? 1 : 0)

Now you can query:

SELECT 
    * 
FROM foo 
WHERE
    bar = $P{bar}
    AND
        (
            some_date > $P{some.date}
            OR 1 = $P{is_null_pram}
        )

I think you can use the function:

$X{EQUAL, <column_name>, <parameter_name>}

It optimizes the query as you can see in this help page.

You can use this conditional statement

    select * 
    from foo 
    where bar = $P{bar} and some_date > $P{some.date} or $P{some.date}  is null
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!