JasperReports: How to add a WHERE statement in SQL query depending on a Boolean parameter?

岁酱吖の 提交于 2019-12-31 03:46:11

问题


How can I add a sub where statement in SQL if my Boolean parameter is true in JasperReports?
For example, I have my SQL as below:

SELECT * FROM shops WHERE region = "Canada" ORDER BY name

If my parameter is true, I would like to add and isactive = 'Y' just before ORDER BY.
Anybody knows how I can achieve this?


回答1:


You can add additional parameter for setting additional clause value. After that you can use $P!{} syntax in query.

The sample:

<parameter name="param" class="java.lang.Boolean"/>
<parameter name="whereCond" class="java.lang.String" isForPrompting="false">
    <defaultValueExpression><![CDATA[$P{param} ? " AND isactive='Y'" : ""]]></defaultValueExpression>
</parameter>
<queryString>
    <![CDATA[SELECT * FROM shops WHERE region='Canada' $P!{whereCond} ORDER BY name]]>
</queryString>



回答2:


You can do that direct in SQL

SELECT * FROM shops WHERE region = "Canada"
AND (@param <> `True` OR isActive = 'Y')
-----^^^^^^^^^^^^^^^^--<< Condition: Your param is not true------
ORDER BY name



回答3:


Try this

select * from shops where region = "Canada"
AND isActive = CASE WHEN @var = 'True' then 'Y' ELSE isActive END
order by name


来源:https://stackoverflow.com/questions/12889023/jasperreports-how-to-add-a-where-statement-in-sql-query-depending-on-a-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!