JasperReports中的条件Where子句 [英] Conditional Where clauses in JasperReports

查看:135
本文介绍了JasperReports中的条件Where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想要一个JasperReport,让用户可以根据需要过滤日期。 SQL如下:

Let's say I want a JasperReport that lets the user filter on a date if they so wish. The SQL is as follows:

select * from foo where bar = $P{bar} and some_date > $P{some.date}

现在,我不希望按某些日期过滤没有通过日期。我发现以下人们使用的kludge:

Now, I don't want to filter by some date if they didn't pass the date in. I found the following kludge that people use:

select * from foo where bar = $P{bar} $P!{some.date.fragment}

some.date.fragment 参数定义为以下默认值:

And the some.date.fragment parameter is defined with the following default:

($P{some.date} == null || $P{some.date}.equals("")) ? "" : "AND some_date >'" + new java.sql.Date($P{some.date}.getTime()).toString() + "'"

这不起作用,因为 toString 不以我的SQL服务器格式输出日期明白。我想让条件仍然使用带有jdbc驱动程序的预准备语句并将参数输入,我只是希望准备好的语句依赖于参数是否为null。可以这样做吗?

This is not working as the toString doesn't output the date in a format that my SQL server understands. I would like to have the conditional still use a prepared statement with the jdbc driver and toss the parameter in, I just want the prepared statement to be dependent on if the parameter is null or not. Can this be done?

推荐答案

在使用 $ P!{} 表达式JDBC-Driver为你做了所有格式化。

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

但如果你使用 $ P!{} 表达你必须自己格式化。

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

这样的事情应该有效:

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

根据您的数据类型,您必须自定义 dd.MM.yyyy HH:mm:ss.SSS

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

如果您不想使用 $ P!{} 表达式,可以使用以下解决方案。

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

我个人不喜欢这种方式。它也可能导致糟糕的执行计划。

如果不想使用 $ P!{} 因为你担心sql注入。只要你的参数 $ P {some.date} 包含一个安全的数据类型,如 java.lang.Date ,这是不必要的。 。

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.

创建参数。我们称之为 $ {is_null_pram} 并使用param class Integer 添加默认表达式:

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)

现在您可以查询:

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

这篇关于JasperReports中的条件Where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆