ceochronos
ceochronos

Reputation: 350

How to use if clauses on queries in iReport

I have the following query:

SELECT COLUMN1, COLUMN2, COUNT(*)  
FROM TABLE  
WHERE COLUMN3 IS NOT NULL  
    AND COLUMN4 = 1  
    AND COLUMN5 = 4  
    AND COLUMN6 = 43  
    AND COLUMN7 = $P{YEAR}  
    AND COLUMN8 = $P{IT}  
GROUP BY COLUMN1, COLUMN2  
ORDER BY COLUMN1 ASC  

I wonder if it is possible to do something like:

SELECT COLUMN1, COLUMN2, COUNT(*)  
FROM TABLE  
WHERE COLUMN3 IS NOT NULL  
    AND COLUMN4 = 1  
    AND COLUMN5 = 4  
    AND COLUMN6 = 43  
    AND COLUMN7 = $P{YEAR}  
    IF ($P{IT} != 'ALL') { AND COLUMN8 = $P{IT} }  
GROUP BY COLUMN1, COLUMN2  
ORDER BY COLUMN1 ASC  

In other words, I want to add to the where clause "AND COLUMN8 = $P{IT}" only if "$P{IT}" value is not "ALL". This means if the report must filter by the column "COLUMN8" or not.

Do someone know if this is possible? Is there other approach that accomplish the work?

I tried to execute the above query but I got a 'Compilation running time'.

Thanks in advance.

Upvotes: 1

Views: 3388

Answers (1)

mdahlman
mdahlman

Reputation: 9400

Yes, you can do that in iReport. But you need to look at it slightly differently. You need a second parameter. Keep $P{IT}, and add $P{IT_SQL}. Give $P{IT_SQL} a default value like this:

$P{IT}.equals("ALL") ? "" : " AND COLUMN8 = '" + $P{IT} + "'"

Then your query should look like this:

SELECT COLUMN1, COLUMN2, COUNT(*)  
FROM TABLE  
WHERE COLUMN3 IS NOT NULL  
    AND COLUMN4 = 1  
    AND COLUMN5 = 4  
    AND COLUMN6 = 43  
    AND COLUMN7 = $P{YEAR}  
    $P!{IT_SQL} 
GROUP BY COLUMN1, COLUMN2  
ORDER BY COLUMN1 ASC

That will give you the desired SQL (none!) when $P{IT} has the value "ALL", and it will give you the desired SQL (COLUMN8 = 'abc') when $P{IT} has the value "abc".

Upvotes: 1

Related Questions