Please convert decode query to case expression
Please convert decode query to case expression
Decode(Sign(id), 1, id, null) positive, Decode(Sign(id), -1, id, null) negative from dual;
this is a serious forums that help people, if you want that we do your "homeworks" i must told you that you should pay us for that.
Edited by: Fran on 05-jun-2013 23:41
1002966
Handle: 1002966
Status Level: Newbie
Registered: Apr 28, 2013
Total Posts: 20
Total Questions: 12 (12 unresolved)
Similar Messages
-
Please convert this query to update.
Hi Experts,
Please convert this MERGE statment to UPDATE.
MERGE INTO CUSTOMER_DTLS CDT
USING
SELECT CDT.CDT_ID, CDT.CDT_ITEMREQ_NO, CDT_UNIT_NO, CDT.CDT_UPDATE_DT, OST.SalesName, OST.Team, OST.Team_ID
FROM CUSTOMER_DTLS CDT
INNER JOIN REVEN_MAP RMP ON CDT.CDT_ID = RMP.ORG_ID
INNER JOIN SALES_DTLS OST ON RMP.WB_IBU = OST.IBU AND OST.Rep_Code = CDT.CDT_SECSALESREP
WHERE CDT.PRODUCT_SEC = 'M'
AND CDT.CDT_ID = 600
) SALES_QUERY
ON(
CDT.CDT_ID = SALES_QUERY.CDT_ID
AND CDT.CDT_ITEMREQ_NO = SALES_QUERY.CDT_ITEMREQ_NO
AND CDT.CDT_UNIT_NO = SALES_QUERY.CDT_UNIT_NO
AND CDT.CDT_UPDATE_DT = SALES_QUERY.CDT_UPDATE_DT
AND CDT.PRODUCT_SEC = 'M'
WHEN MATCHED THEN
UPDATE SET CDT.CDT_SALES_REP = SALES_QUERY.SalesName,
CDT.CDT_OutSide_SALES_DTLS = SALES_QUERY.Team,
CDT.CDT_OutSide_Team_ID = SALES_QUERY.Team_ID
WHERE CDT.CDT_SALES_REP IS NULL
AND CDT.PRODUCT_SEC = 'M'
AND CDT.CDT_ID = 600;
Please help me.
Thanks.Hi All,
The merge query first doing join and make it as a SALES_QUERY query.
SELECT CDT.CDT_ID, CDT.CDT_ITEMREQ_NO, CDT_UNIT_NO, CDT.CDT_UPDATE_DT, OST.SalesName, OST.Team, OST.Team_ID
FROM CUSTOMER_DTLS CDT
INNER JOIN REVEN_MAP RMP ON CDT.CDT_ID = RMP.ORG_ID
INNER JOIN SALES_DTLS OST ON RMP.WB_IBU = OST.IBU AND OST.Rep_Code = CDT.CDT_SECSALESREP
WHERE CDT.PRODUCT_SEC = 'M'
AND CDT.CDT_ID = 600
) SALES_QUERY
On top of it using the result of SALES_QUERY checking the following matching.
ON(
CDT.CDT_ID = SALES_QUERY.CDT_ID
AND CDT.CDT_ITEMREQ_NO = SALES_QUERY.CDT_ITEMREQ_NO
AND CDT.CDT_UNIT_NO = SALES_QUERY.CDT_UNIT_NO
AND CDT.CDT_UPDATE_DT = SALES_QUERY.CDT_UPDATE_DT
AND CDT.PRODUCT_SEC = 'M'
But in your update it's just joining and after that not used any of these values for comparison.
CDT.CDT_ID, CDT.CDT_ITEMREQ_NO, CDT_UNIT_NO, CDT.CDT_UPDATE_DT, OST.SalesName, OST.Team, OST.Team_ID
How this works.
Please explain.
Thanks. -
Please convert this query to UPDATE query.
Hi Experts,
Hello 976208
You can update the columns only in the table which is assigned to the MERGE INTO keywords. -> In this case only in the WEB_SALE_EMP Table.
There is a possibility that you can update / Insert complex codes if and only if this is created as a VIEW!
So, in this case, because you do not have any view on the two tables ( WEB_SALE_EMP and WEB_DELIVERY WD ) you can only update the WEB_SALE_EMP table.
MERGE INTO WEB_SALE_EMP WE
USING
SELECT
WBE.SHIPNT_ID SHIPNT_ID, WBE.SHIPNT_SRC SHIPNT_SRC, WBE.WB_ID WB_ID, WBE.SHIPNO SHIPNO, WBE.TAG_NO TAG_NO,
CAST(COALESCE(WD.VALUE,'0') AS NUMBER) WB_VAL,
SUM(WBE.REV * WBE.AMOUNT) AS Sum_Rev
FROM WEB_SALE_EMP WBE
INNER JOIN WEB_DELIVERY WD ON (WBE.WB_ID = WD.PG_ID AND WD.OPERATION = 'DISCOUNT')
WHERE SHIPMNT_TYPE ='AIR_DISPATCH'
AND WB_ID = p_PG_ID
AND SHIPNT_ID = 2
AND DESCP IS NOT NULL
AND SALE_CODE IS NOT NULL
AND UNIT IS NOT NULL
GROUP BY SHIPNT_ID, SHIPNT_SRC, WB_ID, SHIPNO, TAG_NO,
CAST(COALESCE(WD.VALUE,'0') AS NUMBER)
HAVING SUM(WBE.REV * WBE.AMOUNT) > CAST(COALESCE(WD.VALUE,'0') AS NUMBER)
)v
ON( we.SHIPNT_ID = v.SHIPNT_ID
AND we.SHIPNT_SRC = v.SHIPNT_SRC
AND we.WB_ID = v.WB_ID
AND we.SHIPNO = v.SHIPNO
AND we.TAG_NO = v.TAG_NO
WHEN MATCHED THEN
UPDATE SET we.DELIVERY_TYPE = 'AIR'
WHERE DESCP IS NOT NULL
AND SALE_CODE IS NOT NULL
AND UNIT IS NOT NULL
AND we.WB_ID = 9
AND we.SHIPNT_ID = 3;
Without these columns should your sql works.
I hope this helps you.
Regards,
David
IMPORTANT: Please use always QUALIFIED Column-names in a complex sql code! (Example: wb_id = ... is bad! -> Good: TABLE_ALIAS.wb_id = .... !) -
Case expression error with a select query in the condition
Consider the two query below:
1. The first one use a case expression :
select case when 3 > (select 1 from dual)*2 then 1 else 0 end from dual
2. The equivalent with a decode expression:
select
decode(sign(3-(select 1 from dual)*2),1,1,0) from dual
The first query return an ORA-00905 error but not the second one. It seems that the arithmetic operation (select 1 from dual)*2 cause the error. The folowing query doesn't return this error:
select case when 3 > (select 2 from dual) then 1 else 0 end from dual
I run the test with Oracle 8.1.7.3 Enterprise Edition. Is it a known bug ?
Thomasora8174>select case when 3 > (select 1 from dual)*2 then 1 else 0 end from dual;
select case when 3 > (select 1 from dual)*2 then 1 else 0 end from dual
ERROR at line 1:
ORA-00905: missing keyword
ora8174>select case when 3 > cast((select 1 from dual)*2 as number) then 1 else 0 end from dual;
CASEWHEN3>CAST((SELECT1FROMDUAL)*2ASNUMBER)THEN1ELSE0END
1
1 row selected.
ora8174>select case when 3 > to_number((select 1 from dual)*2) then 1 else 0 end from dual;
CASEWHEN3>TO_NUMBER((SELECT1FROMDUAL)*2)THEN1ELSE0END
1
1 row selected.
ora8174>@connect
Connected.
ora9204>select case when 3 > (select 1 from dual)*2 then 1 else 0 end from dual;
CASEWHEN3>(SELECT1FROMDUAL)*2THEN1ELSE0END
1
1 row selected. -
SQL Expression in decode function or case statement?
Can I put SQL expressions in decode function or case statement?
For example,
select le.profile, decode( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile, 0, 'N', 'Y')
from element le;
or
select le.profile, case WHEN ( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile) = 0 THEN 'N'
ELSE 'Y'
from element le;
None of the above work.
Can anyone tell me how to make it work?
Is there any workaround?
Thanks,
JYou simply needed and END to your CASE statement;
SQL> with profile_data as (
select 'XXXX_AFTER' name, 1 object_id from dual),
element as (
select 1 profile from dual union all
select 2 from dual)
select le.profile,
case WHEN ( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile) = 0
THEN 'N'
ELSE 'Y'
END new_col
from element le
PROFILE N
1 Y
2 N -
Converting Decode function in OBIEE
Hi Guru's
we are converting some BO reports to OBIEE and need to convert Decode function
Below is the Decode function they are using:
Decode ( sign(nvl(BOOKINGS_DATA_UDTC.qty_shipped,0)), 0,decode(BOOKINGS_DATA_UDTC.DELIVERY_NUMBER, 0,decode(BOOKINGS_DATA_UDTC.Schd_Ship_date_fk,to_date('1/1/1990','mm/dd/yyyy'),'Next Month Backlog',decode(sign(nvl(BOOKINGS_DATA_UDTC.Schd_Ship_date_fk, '01-JAN-90') -PAR.PAR_DATE), 1, 'Next Month Backlog', 'Current month will ship')) ,'Awaiting for collection') ,'MTD Shipped')
i have tried converting into case :
case when sign(IFNULL("BOOKINGS_DATA_UDTC"."Qty Shipped",0)) = 0 then (case when "BOOKINGS_DATA_UDTC"."Delivery Number" = 0 then (case when "BOOKINGS_DATA_UDTC"."SCHD_SHIP_DATE_FK" = '01-JAN-1990' then 'Next Month Backlog' else (case when Timestampdiff(SQL_TSI_DAY, cast('@{ParDate}{28-DEC-2012}' as Date),(case when "BOOKINGS_DATA_UDTC"."SCHD_SHIP_DATE_FK" IS NULL then CAst('01-JAN-1990' as DATE) else "BOOKINGS_DATA_UDTC"."SCHD_SHIP_DATE_FK" end)) > 1 then 'Next Month Backlog' else 'Current Month Will Ship' end) end) else 'Awaiting For Collection' end) else 'MTD Shipped' end
But it is not workign as expected.
Can some one please help me with this.
Thanks,you can achieve it by using CASE WHEN condition END function in obiee. nested case also supported by obiee.
check the below link Decode Join Condition in OBIEE RPD
Thanks
Jay.
Edited by: Jay on Apr 3, 2012 12:56 PM -
How to use the CASE Expression in Where Cluase?
Hi All,
I'm trying to use the CASE Expression in the Where Clause at some trigger on the Form?
I've tried this Code:
Declare
N Number;
begin
SELECT COUNT(E.EMP_SID)
INTO N
FROM EMPLOYEES E, RANKS R
WHERE CASE WHEN R.qualification_sid = 1104 AND E.rank_sid = 8 THEN
(TO_DATE(E.RANK_DATE, 'DD-MM-RR')+(365*M.spe_per)+1)
ELSE
(TO_DATE(E.RANK_DATE, 'DD-MM-RR')+(365*M.mili_yea_per)+1)
END
BETWEEN TO_DATE('01-07-2011', 'DD-MM-RR') AND TO_DATE('31-07-2011', 'DD-MM-RR');
END;
When I run this code as a normal query at any SQL editor it works successfully, But When I Compile it at some trigger on the Form it gives me this error:
Encountered the symbol "CASE" when expecting one of the following:
( - + mod ......
Heeey how to specify the previous code to be shown as code in the thread?
Note: I'm using Forms 6iOK I tried it and worked but for one condition:
WHERE DECODE (E.qualification_sid, 1104,
(TO_DATE(E.RANK_DATE, 'DD-MM-RR')+(365*M.spe_per)+1),
(TO_DATE(E.RANK_DATE, 'DD-MM-RR')+(365*M.mili_yea_per)+1))
BETWEEN TO_DATE('01-07-2011', 'DD-MM-RR') AND TO_DATE('31-07-2011', 'DD-MM-RR')
But how to put two conditions for the same Expression:
WHERE DECODE ((E.qualification_sid, 1104) AND (E.RANK_SID, 8),
(TO_DATE(E.RANK_DATE, 'DD-MM-RR')+(365*M.spe_per)+1),
(TO_DATE(E.RANK_DATE, 'DD-MM-RR')+(365*M.mili_yea_per)+1))
BETWEEN TO_DATE('01-07-2011', 'DD-MM-RR') AND TO_DATE('31-07-2011', 'DD-MM-RR')
The previous code gives me this error: missing right parenthesis -
ORABPEL-09503 Invalid xpath expression in a CASE expression
Hi I have the following case statement in my BPEL process -
<switch name="checkAuthenticateResult">
<case condition="upper-case(string(bpws:getVariableData('g_InvokeAuthenticateTicketOutput','OutputParameters','/ns13:OutputParameters/X_RETURN_STATUS')))='S' AND upper-case(string(bpws:getVariableData('g_InvokeAuthenticateTicketOutput','OutputParameters','/ns13:OutputParameters/X_TKT_VALID')bpws:getVariableData('isAuthenticCaller'))) = 'T'">
<bpelx:annotation>
<bpelx:pattern>authenticatePass
</bpelx:pattern>
</bpelx:annotation>
<assign name="assignTktOutput">
<copy>
<from expression="boolean(bpws:getVariableData('g_InvokeAuthenticateTicketOutput','OutputParameters','/ns13:OutputParameters/X_TKT_VALID')='T')"/>
<to variable="outputVariable" part="payload" query="/client:WshSendTxnToOtmServiceProcessResponse/client:result/ns2:authenticated"/>
</copy>
</assign>
</case>
<otherwise>
<throw name="throwAuthenticateFail" faultVariable="g_faultVariable" faultName="faultError"/>
</otherwise>
</switch>
When I run my process in 10.1.2, it works fine, but when I run it in 10.1.3.1, it errors out with the following error -
<Faulthttp://schemas.xmlsoap.org/soap/envelope/>
<faultcode>env:Server</faultcode>
<faultstring>ORABPEL-09503 Invalid xpath expression. Error while parsing xpath expression "upper-case(string(bpws:getVariableData('g_InvokeAuthenticateTicketOutput','OutputParameters','/ns13:OutputParameters/X_RETURN_STATUS')))='S' AND upper-case(string(bpws:getVariableData('g_InvokeAuthenticateTicketOutput','OutputParameters','/ns13:OutputParameters/X_TKT_VALID')bpws:getVariableData('isAuthenticCaller'))) = 'T'", the reason is Unknown expression at EOF: upper-case(string(bpws:getVariableData('g_InvokeAuthenticateTicketOutput','OutputParameters','/ns13:OutputParameters/X_RETURN_STATUS')))='S' AND upper-case(string(bpws:getVariableData('g_InvokeAuthenticateTicketOutput','OutputParameters','/ns13:OutputParameters/X_TKT_VALID')bpws:getVariableData('isAuthenticCaller'))) = 'T'..
Please verify the xpath query "upper-case(string(bpws:getVariableData('g_InvokeAuthenticateTicketOutput','OutputParameters','/ns13:OutputParameters/X_RETURN_STATUS')))='S' AND upper-case(string(bpws:getVariableData('g_InvokeAuthenticateTicketOutput','OutputParameters','/ns13:OutputParameters/X_TKT_VALID')bpws:getVariableData('isAuthenticCaller'))) = 'T'" which is defined in BPEL process.
</faultstring><faultactor></faultactor></env:Fault></env:Body></env:Envelope>
Do you think there was a bug in the expression that has surfaced due to some additional validations in 10.1.3.1 or am I missing something here?
Thanks a lot for your help.
Thanks.
RVAND upper-case(string(bpws:getVariableData('g_InvokeAuthenticateTicketOutput','OutputParameters','/ns13:OutputParameters/X_TKT_VALID')bpws:getVariableData('isAuthenticCaller'))) = 'T'"
what is this bold part about? this looks wrong to me..
/clemens -
Hi all,
I am creating a Java application that - among other useful things - needs to change the values of the DB according a to a huge (maybe > 1000 mappings) , user-created (through the UI) mapping like the one below:
DB Value UI Value
a --> A1
b --> B2
c --> C3
d --> D4
e --> E5
f --> F6
So, if my SELECT contains the column that needs its values changed (the values on the left), I need to somehow get the values on the right.
Normally, I would create a table with this mapping and use it in my query to have it return the values I need. However, I cannot do this, because I don't have (and will not get) privileges to create tables or procedures.
* One solution that comes into my mind is to generate through Java a query with a HUGE case expression, with a case for each mapping. But this does not seem right.
* Another thing I could do is make the query return the DB value and in my application I could do this mapping.
Is there a more elegant way to do the mapping without creating a table in the DB?
Thanks,
Markos
Edited by: user622271 on Jun 23, 2009 6:42 AMYour best bet is a lookup table. If you do not have privilege to create a lookup table for some reason, then you should be allowed to create a view.
I am not sure how many mappings you will finally have, but it sounds like too much to DECODE. But in a simpler circumstance, you could use DECODE directly in your application SQL or use it to create a view then access the view from your application instead of the table.
SELECT DECODE(db_value,
'a','A1',
'b','B2',
'c','C3',
'd','D4',
'x','Xn') ui_value
FROM table_name
/If you are lucky to have your db_value exist with some kind of pattern, then you can reduce the number of lines with some pattern matching. -
Case Expression in when clause
I am doing a query to filter out depto 20 and inside the case deptno 30 only if sal = 1500. Its working fine. I just want to do this without end=1? is there any way.
select * from scott.emp where deptno not in (20)
and case when deptno = 30
AND sal = 1500
THEN 0
ELSE 1
end=1
I am getting error when I remove end=1
ORA-00918: column ambiguously defined
please help me..Hi,
A lot of guys would say:
SELECT *
FROM scott.emp
WHERE deptno <> 20
AND ( deptno <> 30
OR sal <> 1500
);Whenever you use CASE, whether in the WHERE clause or anywhere else, the CASE expression must return a value of some SQL datatype, like NUMBER or VARCHAR2. There is no boolean data type in SQL, so you can't say:
WHERE CASE ... ENDIf you're using CASE in the WHERE clause, you have to say something like
WHERE CASE ... END = 'Okay'or
WHERE CASE ... END NOT IN (0)As G illlustrated, you can hide the CASE statement in a subquery, and use the value it returns in the main query, if you prefer that. -
hi all,
which is better to use in below two query's.
select empno from emp where deptno=10
union all
select empno from emp where deprno=20
or
select
case when deptno=10 then empno end case ,
case when deptno=20 then empno end case
from
emp
which is better?
will case expression in select statement will effect the performance?
regards
shashank .kHi,
shashank .kura wrote:
hi thanks for reply ,
now consider these two Please try the queries yourself before posting them. Ask specific questions, such as "Why does the first query produce ...?" or "I though the second query would produce ... using the standard scott.emp table. Why doesn't it?"
select empno,null from emp where deptno=10
union all
select null,empno from emp where deptno=20The query above will only produce results for rows where deptno=10 or 20 (a total of 8 rows in the standard scott.emp table).
and
select case when deptno=10 then empno else null end case ,
case when deptno=20 then empno else null end case from emp order by 1,2This second query will produce one output row for every row in the table (14 rows in the standatd scott.emp table. 8 of those rows will be the same as returned by the first query, and the other 6 will have NULL in both columns.) Also, both columns have the same alias, CASE. (The keyword to end a CASE expression is just END. If you say END CASE, then CASE is taken to be a column alais.)
The following gets the same results as your first query:
select case
when deptno=10 then empno
else null
end AS empno_10
, case
when deptno=20 then empno
else null
end AS empno_20
from emp
WHERE deptno IN (10, 20)
;This will be more efficient than a UNION, because it only has to make one pass through the table.
Edited by: Frank Kulash on Aug 19, 2011 10:26 AM -
Converting this query to Oracle-Help
New account as my old email address has changed so I had to create a new one. Sucks!
Either way can I please get some help with converting the query below to oracle syntax not microsoft sql. Cheers
select eventtypeid as Payment_Type,
sum(commission_amount) as commission_amount,
startdate as commission_date
from
SELECT distinct
PERIOD.STARTDATE,
Dealer_Hierarchy.SUPER_DISTRIBUTOR_CODE,
case when Dealer_Hierarchy.SUPER_DISTRIBUTOR_CODE in ('2573','185')
then 'D'
when Dealer_Hierarchy.SUPER_DISTRIBUTOR_CODE in ('1126','1055')
then 'O'
when Dealer_Hierarchy.SUPER_DISTRIBUTOR_CODE in ('789','4000','785','871','1028','743')
then 'R'
else Dealer_Hierarchy.SUPER_DISTRIBUTOR_CODE
end as SDC,
Master_Usage.GENERICATTRIBUTE2 AS Service_Id,
Master_Usage.EVENTTYPEID,
sum(Master_Usage.CONTRIBUTIONVALUE) AS Commission_Amount
FROM Master_Usage INNER JOIN PERIOD
ON Master_Usage.PERIODSEQ = PERIOD.PERIODSEQ
INNER JOIN (select distinct
lastname,
super_distributor_code,
distributor_code,
participantid,
startperiod
from Dealer_Hierarchy_107_114
where startperiod in ('107','108','110','111','112','114')
AND NOT POSITIONTYPEID LIKE 'MI %'
and not super_distributor_code = 'null' or distributor_code = 'null') as dealer_hierarchy
ON Master_Usage.GENERICATTRIBUTE1 = dealer_hierarchy.PARTICIPANTID and dealer_hierarchy.startperiod in ('107','108','110','111','112','114')
WHERE
(NOT Master_Usage.PRODUCTID = 'IDDV' OR Master_Usage.PRODUCTID IS NULL)
AND Master_Usage.PERIODSEQ in ('107','108','110','111','112','114')
and Dealer_Hierarchy.startperiod in ('107','108','110','111','112','114')
and Master_Usage.NAME not like '%revenue%'
and Master_Usage.name not like '%GST%'
group by PERIOD.STARTDATE,
Dealer_Hierarchy.SUPER_DISTRIBUTOR_CODE,
Master_Usage.GENERICATTRIBUTE2,
Master_Usage.EVENTTYPEID
) as asf
group by asf.EVENTTYPEID,
startdate
order by commission_amount descplease see the bold section,
could that be the reason ??
select eventtypeid as Payment_Type,
sum(commission_amount) as commission_amount,
startdate as commission_date
from
SELECT distinct
PERIOD.STARTDATE,
Dealer_Hierarchy.SUPER_DISTRIBUTOR_CODE,
case when Dealer_Hierarchy.SUPER_DISTRIBUTOR_CODE in ('2573','185')
then 'D'
when Dealer_Hierarchy.SUPER_DISTRIBUTOR_CODE in ('1126','1055')
then 'O'
when Dealer_Hierarchy.SUPER_DISTRIBUTOR_CODE in ('789','4000','785','871','1028','743')
then 'R'
else Dealer_Hierarchy.SUPER_DISTRIBUTOR_CODE
end as SDC,
Master_Usage.GENERICATTRIBUTE2 AS Service_Id,
Master_Usage.EVENTTYPEID,
sum(Master_Usage.CONTRIBUTIONVALUE) AS Commission_Amount
FROM Master_Usage INNER JOIN PERIOD
ON Master_Usage.PERIODSEQ = PERIOD.PERIODSEQ
INNER JOIN (select distinct
lastname,
super_distributor_code,
distributor_code,
participantid,
startperiod
from Dealer_Hierarchy_107_114
where startperiod in ('107','108','110','111','112','114')
AND NOT POSITIONTYPEID LIKE 'MI %'
and not (super_distributor_code = 'null' or distributor_code = 'null') as dealer_hierarchy
ON Master_Usage.GENERICATTRIBUTE1 = dealer_hierarchy.PARTICIPANTID and dealer_hierarchy.startperiod in ('107','108','110','111','112','114')
WHERE
(NOT Master_Usage.PRODUCTID = 'IDDV' OR Master_Usage.PRODUCTID IS NULL)
AND Master_Usage.PERIODSEQ in ('107','108','110','111','112','114')
and Dealer_Hierarchy.startperiod in ('107','108','110','111','112','114')
and Master_Usage.NAME not like '%revenue%'
and Master_Usage.name not like '%GST%'
group by PERIOD.STARTDATE,
Dealer_Hierarchy.SUPER_DISTRIBUTOR_CODE,
Master_Usage.GENERICATTRIBUTE2,
Master_Usage.EVENTTYPEID
) as asf
group by asf.EVENTTYPEID,
startdate
order by commission_amount desc -
CASE STATEMENTS AND CASE EXPRESSIONS IN ORACLE9I PL/SQL
제품 : PL/SQL
작성날짜 : 2001-11-13
CASE STATEMENTS AND CASE EXPRESSIONS IN ORACLE9I PL/SQL
=======================================================
PURPOSE
아래의 자료는 Case 문에서 oracle 8.1.7과 Oracle 9i의 New Feature로 8.1.7에서는
sqlplus 에서만 가능했고, 9i 부터는 pl/sql 까지 가능하다.
Explanation
1. Oracle 8.1.7 Feature
Oracle 8.1.7 에서 Case 문은 Decode 문과 유사하지만, 기존의 decode 문을 쓰는 것보다
더 많은 확장성과 Logical Power와 좋은 성능을 제공한다. 주로 나이와 같이 category 별로
나눌때 주로 사용하고 Syntex는 아래와 같다.
CASE WHEN <cond1> THEN <v1> WHEN <cond2> THEN <v2> ... [ELSE <vn+1> ] END
각각의 WHEN...THEN 절의 argument 는 255 까지 가능하고 이 Limit를 해결하려면
Oracle 8i Reference를 참조하면 된다.
The maximum number of arguments in a CASE expression is 255, and each
WHEN ... THEN pair counts as two arguments. To avoid exceeding the limit of 128 choices,
you can nest CASE expressions. That is expr1 can itself be a CASE expression.
Case Example : 한 회사의 모든 종업원의 평균 봉급을 계산하는데 봉급이 $2000보다 작은경우
2000으로 계산을 하는 방법이 pl/sql을 대신하여 case function을 사용할 수 있다.
SELECT AVG(CASE when e.sal > 2000 THEN e.sal ELSE 2000 end) FROM emp e;
Case Example : 나이를 column으로 가지고 있는 customer table을 예로 들어보자.
SQL> SELECT
2 SUM(CASE WHEN age BETWEEN 70 AND 79 THEN 1 ELSE 0 END) as "70-79",
3 SUM(CASE WHEN age BETWEEN 80 AND 89 THEN 1 ELSE 0 END) as "80-89",
4 SUM(CASE WHEN age BETWEEN 90 AND 99 THEN 1 ELSE 0 END) as "90-99",
5 SUM(CASE WHEN age > 99 THEN 1 ELSE 0 END) as "100+"
6 FROM customer;
70-79 80-89 90-99 100+
4 2 3 1
1 SELECT
2 (CASE WHEN age BETWEEN 70 AND 79 THEN '70-79'
3 WHEN age BETWEEN 80 and 89 THEN '80-89'
4 WHEN age BETWEEN 90 and 99 THEN '90-99'
5 WHEN age > 99 THEN '100+' END) as age_group,
6 COUNT(*) as age_count
7 FROM customer
8 GROUP BY
9 (CASE WHEN age BETWEEN 70 AND 79 THEN '70-79'
10 WHEN age BETWEEN 80 and 89 THEN '80-89'
11 WHEN age BETWEEN 90 and 99 THEN '90-99'
12* WHEN age > 99 THEN '100+' END)
SQL> /
AGE_G AGE_COUNT
100+ 1
70-79 4
80-89 2
90-99 3
Example
2. Oracle 9i Feature
Oracle 9i부터는 pl/sql에서도 case문을 사용할 수 있으면 이것은
복잡한 if-else 구문을 없애고, C언어의 switch문과 같은 기능을 한다.
아래의 9i pl/sql Sample 및 제약 사항을 보면 아래와 같다.
Sample 1:
A simple example demonstrating the proper syntax for a case
statement
using a character variable as the selector. See the section entitled
'Restrictions' at the end of this article for details on which PLSQL
datatypes may appear as a selector in a case statement or
expression.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
achar char(1) := '&achar';
begin
case achar
when 'A' then dbms_output.put_line('The description was Excellent');
when 'B' then dbms_output.put_line('The description was Very Good');
when 'C' then dbms_output.put_line('The description was Good');
when 'D' then dbms_output.put_line('The description was Fair');
when 'F' then dbms_output.put_line('The description was Poor');
else dbms_output.put_line('The description was No such Grade');
end case;
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 2:
A simple example demonstrating the proper syntax for a case
expression
using a character variable as the selector. See the section entitled
'Restrictions' at the end of this article for details on which PLSQL
datatypes may appear as a selector in a case statement or
expression.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
achar char(1) := '&achar';
description varchar2(20);
begin
description :=
case achar
when 'A' then 'Excellent'
when 'B' then 'Very Good'
when 'C' then 'Good'
when 'D' then 'Fair'
when 'F' then 'Poor'
else 'No such grade'
end;
dbms_output.put_line('The description was ' || description);
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
NOTE: The above simple samples demonstrate two subtle differences in the
syntax
required for case statements and expressions.
1) A case STATEMENT is terminated using the 'end case' keywords; a
case
EXPRESSION is terminated using only the 'end' keyword.
2) Each item in a case STATEMENT consists of one or more
statements, each
terminated by a semicolon. Each item in a case expression
consists of
exactly one expression, not terminated by a semicolon.
Sample 3:
Sample 1 demonstrates a simple case statement in which the selector
is
compared for equality with each item in the case statement body.
PL/SQL
also provides a 'searched' case statement as an alternative; rather
than
providing a selector and a list of values, each item in the body of
the
case statement provides its own predicate. This predicate can be any
valid boolean expression, but only one case will be selected.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
achar char(1) := '&achar';
begin
case
when achar = 'A' then dbms_output.put_line('The description was
Excellent');
when achar = 'B' then dbms_output.put_line('The description was Very
Good');
when achar = 'C' then dbms_output.put_line('The description was
Good');
when achar = 'D' then dbms_output.put_line('The description was
Fair');
when achar = 'F' then dbms_output.put_line('The description was
Poor');
else dbms_output.put_line('The description was No such Grade');
end case;
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 4:
This sample demonstrates the proper syntax for a case expression of
the
type discussed in Sample 3 above.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
achar char(1) := '&achar';
description varchar2(20);
begin
description :=
case
when achar = 'A' then 'Excellent'
when achar = 'B' then 'Very Good'
when achar = 'C' then 'Good'
when achar = 'D' then 'Fair'
when achar = 'F' then 'Poor'
else 'No such grade'
end;
dbms_output.put_line('The description was ' || description);
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 5:
This sample demonstrates the use of nested case statements. It is
also
permissable to nest case expressions within a case statement (though
it
is not demonstrated here), but nesting of case statements within a
case
expression is not possible since statements do not return any value.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
anum1 number := &anum1;
anum2 number := &anum2;
answer number;
begin
case anum1
when 1 then case anum2
when 1 then answer := 10;
when 2 then answer := 20;
when 3 then answer := 30;
else answer := 999;
end case;
when 2 then case anum2
when 1 then answer := 15;
when 2 then answer := 25;
when 3 then answer := 35;
else answer := 777;
end case;
else answer := 555;
end case;
dbms_output.put_line('The answer is ' || answer);
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 6:
This sample demonstrates nesting of case expressions within another
case
expression. Note again the absence of semicolons to terminate both
the
nested case expression and the individual cases of those
expressions.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
anum1 number := &anum1;
anum2 number := &anum2;
answer number;
begin
answer :=
case anum1
when 1 then case anum2
when 1 then 10
when 2 then 20
when 3 then 30
else 999
end
when 2 then case anum2
when 1 then 15
when 2 then 25
when 3 then 35
else 777
end
else 555
end;
dbms_output.put_line('The answer is ' || answer);
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Although PL/SQL anonymous blocks have been used in all of the examples
so far,
case statements and expressions can also be used in procedures,
functions, and
packages with no changes to the syntax.
The following samples are included for completeness and demonstrate the
use of
case statements and/or expressions in each of these scenarios.
Sample 7:
This sample demonstrates use of a case statement in a stored
procedure.
Note that this sample also demonstrates that it is possible for each
of
the items in the case body to consist of more than one statement.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
create or replace procedure testcasestmt ( anum IN number ) is
begin
case
when anum = 1 then dbms_output.put_line('The number was One');
dbms_output.put_line('In case 1');
when anum = 2 then dbms_output.put_line('The number was Two');
dbms_output.put_line('In case 2');
when anum = 3 then dbms_output.put_line('The number was Three');
dbms_output.put_line('In case 3');
when anum = 4 then dbms_output.put_line('The number was Four');
dbms_output.put_line('In case 4');
when anum = 5 then dbms_output.put_line('The number was Five');
dbms_output.put_line('In case 5');
else dbms_output.put_line('The description was Invalid input');
dbms_output.put_line('In the else case');
end case;
end;
exec testcasestmt(&anum);
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 8:
This sample demonstrates the use of a case statement in a stored
package.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
create or replace package testpkg2 is
procedure testcasestmt ( anum IN number );
function testcasestmt_f ( anum IN number ) return number;
end testpkg2;
create or replace package body testpkg2 is
procedure testcasestmt ( anum IN number ) is
begin
case
when anum = 1 then dbms_output.put_line('The number was One');
dbms_output.put_line('In case 1');
when anum = 2 then dbms_output.put_line('The number was Two');
dbms_output.put_line('In case 2');
when anum = 3 then dbms_output.put_line('The number was Three');
dbms_output.put_line('In case 3');
when anum = 4 then dbms_output.put_line('The number was Four');
dbms_output.put_line('In case 4');
when anum = 5 then dbms_output.put_line('The number was Five');
dbms_output.put_line('In case 5');
else dbms_output.put_line('The description was Invalid input');
dbms_output.put_line('In the else case');
end case;
end;
function testcasestmt_f ( anum IN number ) return number is
begin
case
when anum = 1 then dbms_output.put_line('The number was One');
dbms_output.put_line('In case 1');
when anum = 2 then dbms_output.put_line('The number was Two');
dbms_output.put_line('In case 2');
when anum = 3 then dbms_output.put_line('The number was Three');
dbms_output.put_line('In case 3');
when anum = 4 then dbms_output.put_line('The number was Four');
dbms_output.put_line('In case 4');
when anum = 5 then dbms_output.put_line('The number was Five');
dbms_output.put_line('In case 5');
else dbms_output.put_line('The description was Invalid input');
dbms_output.put_line('In the else case');
end case;
return anum;
end;
end testpkg2;
exec testpkg2.testcasestmt(&anum);
variable numout number
exec :numout := testpkg2.testcasestmt_f(&anum);
print numout
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 9:
This sample demonstrates the use of a case expression in a stored
package.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
create or replace package testpkg is
procedure testcase ( anum IN number );
function testcase_f ( anum IN number ) return number;
end testpkg;
create or replace package body testpkg is
procedure testcase ( anum IN number ) is
anumber number := anum;
anothernum number;
begin
anothernum :=
case
when anumber = 1 then anumber + 1
when anumber = 2 then anumber + 2
when anumber = 3 then anumber + 3
when anumber = 4 then anumber + 4
when anumber = 5 then anumber + 5
else 999
end;
dbms_output.put_line('The number was ' || anothernum);
end;
function testcase_f ( anum IN number ) return number is
anumber number := anum;
anothernum number;
begin
anothernum :=
case
when anumber = 1 then anumber + 1
when anumber = 2 then anumber + 2
when anumber = 3 then anumber + 3
when anumber = 4 then anumber + 4
when anumber = 5 then anumber + 5
else 999
end;
dbms_output.put_line('The number was ' || anothernum);
return anothernum;
end;
end testpkg;
variable numout number
exec testpkg.testcase(&anum);
exec :numout := testpkg.testcase_f(&anum);
print numout
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
제약 사항
다음의 databasetype은 case 문에서 지원되지 않는다.
BLOB
BFILE
VARRAY
Nested Table
PL/SQL Record
PL/SQL Version 2 tables (index by tables)
Object type (user-defined type)
All of these types except for object types face a similar restriction
even for if statements (i.e. they cannot be compared for equality directly) so this is unlikely to change for these types. Lack of support for object types is simply an implementation restriction which may be relaxed in future releases.
Reference Ducumment
Oracle 8.1.7 Manual
NOTE:131557.1I have done the following code but doesn't
like the statement of - "case(butNext)". What do you mean "doesn't like" -- did you get an error message?
I'm guessing it won't compile because you're trying to switch on a Button.
I tried something
like "g.fillOval(100,50,70,90, BorderLayout.NORTH)"...no that doesn't make sense. You only use BorderLayout.NORTH when you're adding components to a BorderLayout layout manager. An oval is not a component and fillOval isn't adding a component and Graphics is not a Panel or layout manager.
Would appreciate it if someone could tell me how to position
shapes using the graohic method. I think the problem is that you're confusing shapes with components. -
Oracle:how to use max() function in case expression
how to use max() function in case expression, Please explain with any example
Hope this helps and should be self explanatory
with t as
(select 1 col,100 col2 from dual union
select 2 ,100 from dual union
select 2 ,200 from dual union
select 3,100 from dual union
select 3,200 from dual )
select col, case when max(col2)=100 then 'with 100 range'
when max(col2)=200 then 'with 200 range' end from t group by col -
How to convert sql query to oracle query?
Hi all,
Hope doing well,
sir i am using oracle database where i am running my sql query in oracle. but this query is not working properly. i used sql developer translation scratch editor to convert that.
it's converted but i am not getting the exact value.
which i was getting in sql server.
here is my query below:
SELECT C.*,ISNULL(P.Comp_Name,'') + ' (' + ISNULL(P.Comp_ID,'') + ')' Parent FROM Comp_Master C LEFT JOIN Comp_Master P ON C.Parent_ID = P.Comp_ID Where C.Comp_ID='C02'
please convert it into oracle so that i can use this query
thanks in advance.Try --
1. Use NVL instead of isNull
2. Use *||* instead of +*
/* Formatted on 9-13-2012 4:39:09 PM (QP5 v5.163.1008.3004) */
SELECT c.*, NVL (p.comp_name, '') || ' (' || NVL (p.comp_id, '') || ')' parent
FROM comp_master c LEFT JOIN comp_master p ON c.parent_id = p.comp_id
WHERE c.comp_id = 'C02'
PS - Do remember to mark the solutions as Helpful or Correct. Thanks for understanding.
Maybe you are looking for
-
Ipod Classic connected but not showing in Itunes under Devices
I know this is similar to a few of the other issues that are described, if anyone can offer a link to another thread where the resolution is posted, that would be great, thanks! I plug my ipod into my computer, I get a windows message saying some fil
-
How to Open up Ports to get Open Connection on Xbox 360 on WRT160N V2.
I have the port numbers but do not know how to proceed from there. Step by step instructions and help would be most appreciated. Router is a WRT160N V2. Thanks Solved! Go to Solution.
-
PCA Manual Posting - Stopping posting to certain account
Dear experts, How can I stop usage of a certain account for manual PCA postings thru 9KE0. This is only for manual, the other transactions should be able to post. Any inputs, highly appreciated. Thanks
-
Applications crash on open or save dialogs
This afternoon, my machine started having trouble. When I go to File -> Save or File -> Open in any application, that application crashes. I think it might have been after opening a document from a Parallels virtual machine and trying to have it to t
-
Man... Just found out after build several web sites that, if you want a browser to show a title other than the explicit name of the page in the left column, you need to edit the text in the header. Easy enough. So now, in an existing web site I've bu