0

Is there a way that I can use if statement in a select statement?

I cannot use Case statement in this one. Actually I am using iReport and I have a parameter. What I want to do is if a user does not enter a certain parameter it will select all the instances.

For example a table of person referencing to gender table, a with a parameter on where clause, query would go like:

SELECT * FROM persontable WHERE gender_id = $P{genderName}:numeric

If the parameter $P{genderName} is null or blank then it will select all. I tried this query:

SELECT * FROM persontable WHERE gender_id IN (SELECT CASE WHEN $P{genderName} 
 IS NULL THEB (SELECT id from genderTable 
 WHERE id = $P{genderName}:numeric) ELSE $P{genderName}::numeric END)

But it will return an error "More that one row is returned....." I think it is because of the CASE statement. How do I this?

4

2 回答 2

3

尝试这个:

SELECT * FROM persontable 
WHERE gender_id = $P{genderName} OR $P{genderName} IS NULL 
于 2012-11-10T07:45:09.447 回答
1

这可以使用辅助参数轻松实现。

在您的报告中定义一个新参数,将其命名为aux_gendername.

在定义参数时,调整其Default Value Expression

($P{gendername}.equals("") || $P{gendername}==NULL? " " : " and gender_id = '"+$P{gendername}+"'")

然后在您的主查询中,使用辅助参数而不是实际参数 ($P{gendername})。

SELECT * FROM persontable WHERE 1=1 $P!{aux_gendername}

如果 $P{gendername} 包含任何值,并且条件将动态附加到查询中,否则整个结果集将显示在报告中而无需任何过滤。

注意:使用! 在辅助参数中是强制性的。

于 2012-12-07T12:11:10.353 回答