I'm trying to select and add a where clause only if a certain variable is true. For example:
SELECT *
FROM STUDENTS
WHERE STUDENT_NAME IN ('John', 'Jane');
And my variable is $P{isJohnOrJane}
which can be 0 or 1;
I've tried
SELECT *
FROM STUDENTS
WHERE $P{isJohnOrJane} = 1
AND STUDENT_NAME IN ('John', 'Jane')
and that works. But when ${isJohnOrJane} = 0
it does not select anything when it should select all the students.
1条答案
按热度按时间wljmcqd81#
I'm going to use proper SQL declared variables. There are 2 ways to do this: use the variable directly in the query; or use it to determine the query to execute.
First example using the variable directly in the SQL query:
Alternatively you can use IF logic to determine the execution:
Both will produce the same answer but IF logic works better to avoid weird looking queries containing variables, it uses indexes on table columns as intended, it is probably easier for others to understand, and can apply to multiple outcomes instead of just 2 like in your example.