I have a SQL report. I want to pass a new parameter to this and this parameter should decide below 3 outputs.
select * from po_distributions_all:
encumbered_amount is one of the column.
Parameter Value = P, return all rows with encumbered_amount values which are > zero
Parameter Value = N, return all with encumbered_amount values which are < zero.
Parameter Value = E, return all encumbered_amount values not equal to zero
Parameter as Blank, return all the rows.
I know I can achieve this by a union query.
Is there a way I can achieve without a union?
The query is already a lengthy one. For the simplicity of this question I mentioned it as a single line query above.
CodePudding user response:
What about dynamic SQL?
sqlstr VARCAR2(1000);
cur SYS_REFCURSOR;
BEGIN
sqlstr := 'select * from po_distributions_all';
IF Parameter = 'P' THEN
sqlstr := sqlstr || ' WHERE encumbered_amount > 0';
ELSEIF Parameter = 'N' THEN
sqlstr := sqlstr || ' WHERE encumbered_amount < 0';
ELSEIF Parameter = 'E' THEN
sqlstr := sqlstr || ' WHERE encumbered_amount <> 0';
ELSEIF Parameter IS NULL THEN
NULL;
ELSE
RAISE VALUE_ERROR;
END IF;
OPEN cur FOR sqlstr;
...
END;
CodePudding user response:
You could do this in the where clause:
WHERE
(( :parameter = 'P' AND encumbered_amount > 0 ) OR
( :parameter = 'N' AND encumbered_amount < 0 ) OR
( :parameter = 'E' AND encumbered_amount != 0 ) OR
( :parameter IS NULL )
)
CodePudding user response:
How about CASE
expression? Could've been simpler if there were no E
option :)
This is a SQL*Plus example; depending on tool you use, its '&¶meter'
substitution variable could be :parameter
or something else.
SQL> WITH
2 po_distributions_all (encumbered_amount)
3 AS
4 (SELECT -200 FROM DUAL
5 UNION ALL
6 SELECT 100 FROM DUAL
7 UNION ALL
8 SELECT 0 FROM DUAL)
9 SELECT *
10 FROM po_distributions_all
11 WHERE ( CASE
12 WHEN '&¶meter' <> 'E'
13 OR '&¶meter' IS NULL
14 THEN
15 SIGN (encumbered_amount)
16 END =
17 CASE
18 WHEN '&¶meter' = 'P' THEN 1
19 WHEN '&¶meter' = 'N' THEN -1
20 WHEN '&¶meter' IS NULL THEN SIGN (encumbered_amount)
21 END
22 OR CASE WHEN '&¶meter' = 'E' THEN encumbered_amount END <> 0);
Enter value for parameter: P
ENCUMBERED_AMOUNT
-----------------
100
Negative values:
SQL> UNDEFINE PARAMETER
SQL> /
Enter value for parameter: N
ENCUMBERED_AMOUNT
-----------------
-200
All values except zero:
SQL> UNDEFINE PARAMETER
SQL> /
Enter value for parameter: E
ENCUMBERED_AMOUNT
-----------------
-200
100
All values (parameter's value is NULL
):
SQL> UNDEFINE PARAMETER
SQL> /
Enter value for parameter:
ENCUMBERED_AMOUNT
-----------------
-200
100
0
SQL>