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,
J
You 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
Similar Messages
-
How can i use this expression in DECODE function?
My PNO table formart is
PNO PDate PCount
P001 08/27/05 09:45 20
P001 08/27/05 09:50 10
P002 08/27/05 03:40 20
P003 08/28/05 11:00 20
P003 09/28/05 10:00 20
P003 08/27/05 11:00 10
P003 09/27/05 04:00 50
I want to display total pcount for shift1(morning) and shift2(evening) & the date is 08/27/05
PNO Shift1(08/27/2005 08:00 to 12:30) Shift2(08/27/2005 02:00 to 05:30)
P001 30 0
P002 0 20
P004 10 50
So for shift1 condition is:
pdate>=08/27/2005 08:00 and pdate<=08/27/2005 12:30
So for shift2 condition is:
pdate>=08/27/2005 02:00 and pdate<=08/27/2005 05:30
If i tried to give this expression in decode function , its not working.
Please give me the sql query to solve this problem.
Millions of thanks in advacneforgot to paste the output for a given date.
SQL> create table pno
2 (pno varchar2(32)
3 ,pdate date
4 ,pcount number)
5 /
Table created.
SQL>
SQL> insert into pno values('P001', to_Date('08/27/05 09:45', 'mm/dd/yy hh:mi') ,20)
2 /
1 row created.
SQL> insert into pno values('P001', to_Date('08/27/05 09:50', 'mm/dd/yy hh:mi') ,10)
2 /
1 row created.
SQL> insert into pno values('P002', to_Date('08/27/05 03:40', 'mm/dd/yy hh:mi') ,20)
2 /
1 row created.
SQL>
SQL> insert into pno values('P003', to_Date('08/28/05 11:00', 'mm/dd/yy hh:mi') ,20)
2 /
1 row created.
SQL> insert into pno values('P003', to_Date('09/28/05 10:00', 'mm/dd/yy hh:mi') ,20)
2 /
1 row created.
SQL> insert into pno values('P003', to_Date('08/27/05 11:00', 'mm/dd/yy hh:mi') ,10)
2 /
1 row created.
SQL> insert into pno values('P003', to_Date('09/27/05 04:00', 'mm/dd/yy hh:mi') ,50)
2 /
1 row created.
SQL> select pno,sum(pcount) "Morning Shift Count"
2 from pno
3 where to_char(pdate, 'mm/dd/yyyy hh:mi') >= '08/27/2005 08:00'
4 and to_char(pdate, 'mm/dd/yyyy hh:mi') <='08/27/2005 12:30'
5 group by pno
6 /
PNO Morning Shift Count
P001 30
P003 10
SQL> select pno,sum(pcount) "Evening Shift Count"
2 from pno
3 where to_char(pdate, 'mm/dd/yyyy hh:mi') >= '08/27/2005 02:00'
4 and to_char(pdate, 'mm/dd/yyyy hh:mi') <='08/27/2005 05:30'
5 group by pno
6 /
PNO Evening Shift Count
P002 20 -
Problem in using aggregate functions inside case statement
Hi All,
I am facing problem while using aggregate functions inside case statement.
CASE WHEN PSTYPE='S' THEN MAX(DECODE(POS.PBS,1,ABS(POS.PPRTQ),0)) ELSE SUM(DECODE(POS.PBS,1,ABS(POS.PPRTQ),0)) END,
how can I achieve above requirement ? Con anyone help me.
Thanks and Regards
DGHi All,
Below is my query:
SELECT
CASE WHEN p_reportid IN ('POS_RV_SN','POS_PB') THEN POS.PACCT
ELSE POS.PACCT || '-' || DECODE(POS.SYSTEMCODE,'GMI1','1', 'GMI2','2', 'GMI3','4', 'GMI4','3', '0') ||POS.PFIRM|| NVL(POS.POFFIC,'000') END,
CASE WHEN p_reportid IN ('POS_RV_SN','POS_PB') THEN POS.PACCT||POS.PCUSIP||DECODE(POS.PBS,1,'+',2,'-')
ELSE POS.PFIRM||POS.POFFIC||POS.PACCT||POS.PCUSIP||DECODE(POS.PBS,1,'+',2,'-') END,POS.SYSTEMCODE,CASE WHEN POS.PSTYPE='S' THEN POS.PSYMBL ELSE POS.PFC END,POS.PEXCH||DECODE(POS.PSUBEX,'<NULL>',''),
POS.PCURSY,
CASE WHEN POS.PSBCUS IS NULL THEN SUBSTR(POS.PCTYM,5,2) || SUBSTR(POS.PCTYM,1,4) ELSE POS.PSBCUS || SUBSTR(POS.PCTYM,5,2) || SUBSTR(POS.PCTYM,1,4) END ,
NVL(POS.PSUBTY,'F') ,POS.PSTRIK,*SUM(DECODE(POS.PBS,1,ABS(POS.PPRTQ),0)) ,SUM(DECODE(POS.PBS,2,ABS(POS.PPRTQ),0))* ,
POS.PCLOSE,SUM(POS.PMKVAL) ,
TO_CHAR(CASE WHEN INSTR(POS.PUNDCP,'.') > 0 OR LENGTH(POS.PUNDCP) < 15 THEN POS.PUNDCP ELSE TO_CHAR(TO_NUMBER(POS.PUNDCP) / 100000000) END),
POS.UBS_ID,POS.BBG_EXCHANGE_CODE,POS.BBG_TICKER ,POS.BBG_YELLOW_KEY,POS.PPCNTY,POS.PMULTF,TO_CHAR(POS.BUSINESS_DATE,'YYYYMMDD'),
POS.SOURCE_GMI_LIB,
--DECODE(POS.SYSTEMCODE,'GMI1','euro','GMI2','namr','GMI3','aust','GMI4','asia','POWERBASE','aust','SINACOR','namr',POS.SYSTEMCODE),
DECODE(p_reportid,'RVPOS_SING','euro','RVPOS_AUSTDOM','aust','RVPOS_AUSTEOD','euro','RVPOS_GLBLAPAC','asia','POS_RV_SN','namr','POS_PB','aust',POS.SYSTEMCODE),
POS.RIC,
CASE WHEN PSUBTY = 'S' THEN POS.TYPE ELSE NULL END,
DECODE(POS.UBS_ID,NULL,POS.PCUSP2,POS.ISIN),POS.UNDERLYING_BBG_TICKER,POS.UNDERLYING_BBG_EXCHANGE,POS.PRODUCT_CLASSIFICATION,
CASE WHEN PSUBTY = 'S' THEN POS.PSDSC2 ELSE NULL END,
CASE WHEN PSUBTY = 'S' THEN C.SSDSC3 ELSE NULL END,
NVL(C.SSECID,POS.PCUSIP),
NULL,
POS.PYSTMV,
POS.PMINIT,
POS.PEXPDT,
CASE WHEN POS.PSUBTY='S' THEN SUBSTR(C.ZDATA2,77,1) ELSE NULL END,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
FROM POSITIONS_WRK POS LEFT OUTER JOIN
(SELECT * FROM CDS_PRODUCTS CP INNER JOIN FUTURE_MASTER FM ON
(CP.STRXCH=FM.ZEXCH AND CP.SFC=FM.ZFC AND CP.BUSINESS_DATE = FM.BUSINESS_DATE )) C ON POS.PCUSIP = C.SCUSIP
AND NVL(POS.PCUSP2,'X') = NVL(C.SCUSP2,'X')
WHERE
POS.PEXCH NOT IN ('A1','A2','A3','B1','B3','C2','D1','H1','K1','L1','M1','M3','P1','S1')
AND (POS.PSBCUS IS NOT NULL OR POS.PCTYM IS NOT NULL OR POS.PSTYPE ='S')
AND POS.BUSINESS_DATE = run_date_char
GROUP BY
POS.UBS_ID,POS.SYSTEMCODE,POS.RECIPIENTCODE,POS.BUSINESS_DATE,POS.PACCT,POS.PFIRM,POS.POFFIC,POS.PCUSIP,POS.PBS,CASE WHEN POS.PSTYPE='S' THEN POS.PSYMBL ELSE POS.PFC END,
POS.PEXCH,POS.PSUBEX,POS.PCURSY,
CASE WHEN POS.PSBCUS IS NULL THEN SUBSTR(POS.PCTYM,5,2) || SUBSTR(POS.PCTYM,1,4) ELSE POS.PSBCUS || SUBSTR(POS.PCTYM,5,2) || SUBSTR(POS.PCTYM,1,4) END,
NVL(POS.PSUBTY,'F') ,POS.PSTRIK,POS.PCLOSE,TO_CHAR(CASE WHEN INSTR(POS.PUNDCP,'.') > 0 OR LENGTH(POS.PUNDCP) < 15 THEN POS.PUNDCP ELSE TO_CHAR(TO_NUMBER(POS.PUNDCP) / 100000000) END),
POS.BBG_EXCHANGE_CODE,POS.BBG_TICKER,POS.BBG_YELLOW_KEY,POS.PPCNTY,POS.PMULTF,POS.PSUBTY,POS.SOURCE_GMI_LIB,RIC,
CASE WHEN PSUBTY = 'S' THEN POS.TYPE ELSE NULL END,
DECODE(POS.UBS_ID,NULL,POS.PCUSP2,POS.ISIN),POS.UNDERLYING_BBG_TICKER,POS.UNDERLYING_BBG_EXCHANGE,POS.PRODUCT_CLASSIFICATION,
CASE WHEN PSUBTY = 'S' THEN POS.PSDSC2 ELSE NULL END,
CASE WHEN PSUBTY = 'S' THEN C.SSDSC3 ELSE NULL END,
NVL(C.SSECID,POS.PCUSIP),
POS.PYSTMV,
POS.PMINIT,
POS.PEXPDT,
CASE WHEN PSUBTY = 'S' THEN SUBSTR(C.ZDATA2,77,1) ELSE NULL END;Now, could you plz help me in replacing the bold text in the query with the requirement.
Thanks and Rgds
DG
Edited by: BluShadow on 16-May-2011 09:39
added {noformat}{noformat} tags. Please read: {message:id=9360002} for details on how to post code/data -
Decode function in Update statement
Hello everyone,
I'm trying to write a query where I can update a pastdue_fees column in a book_trans table based on a difference between return_dte and due_dte columns.
I am using Oracle SQL. This is what I have so far for my decode function:
SQL> SELECT
2 DECODE(SIGN((return_dte - due_dte)*2),
3 '-1', '0',
4 '1', '12', 'Null')
5 FROM book_trans;
DECO
Null
12
Null
0
So the logic is that if the sign is -1, the value in return_dte column should be 0; if it's +1 then it's 12 and everything else is Null.
So now, I need to enter my decode function into the update statement to update the columns. However, I get error messages.
The logic should be:
UPDATE book_trans SET PastDue_fees = decode(expression)
I've given it a couple of different tries with the following results:
SQL> UPDATE book_trans
2 SET pastdue_fees = SELECT
3 DECODE(SIGN((return_dte - due_dte)*2),
4 '-1', '0',
5 '1', '12', 'Null')
6 FROM book_trans;
SET pastdue_fees = SELECT
ERROR at line 2:
ORA-00936: missing expression
SQL> UPDATE book_trans
2 SET pastdue_fees =
3 DECODE(SIGN((return_dte - due_dte)*2),
4 '-1', '0',
5 '1', '12', 'Null')
6 FROM book_trans;
FROM book_trans
ERROR at line 6:
ORA-00933: SQL command not properly ended
Any help or tips would be greatly appreciated as I've been taking SQL for about six weeks and not very proficient!
Thanks!882300 wrote:
Hello everyone,
I'm trying to write a query where I can update a pastdue_fees column in a book_trans table based on a difference between return_dte and due_dte columns.
I am using Oracle SQL. This is what I have so far for my decode function:
SQL> SELECT
2 DECODE(SIGN((return_dte - due_dte)*2),
3 '-1', '0',
4 '1', '12', 'Null')
5 FROM book_trans;
DECO
Null
12
Null
0
So the logic is that if the sign is -1, the value in return_dte column should be 0; if it's +1 then it's 12 and everything else is Null.
So now, I need to enter my decode function into the update statement to update the columns. However, I get error messages.
The logic should be:
UPDATE book_trans SET PastDue_fees = decode(expression)
I've given it a couple of different tries with the following results:
SQL> UPDATE book_trans
2 SET pastdue_fees = SELECT
3 DECODE(SIGN((return_dte - due_dte)*2),
4 '-1', '0',
5 '1', '12', 'Null')
6 FROM book_trans;
SET pastdue_fees = SELECT
ERROR at line 2:
ORA-00936: missing expression
SQL> UPDATE book_trans
2 SET pastdue_fees =
3 DECODE(SIGN((return_dte - due_dte)*2),
4 '-1', '0',
5 '1', '12', 'Null')
6 FROM book_trans;
FROM book_trans
ERROR at line 6:
ORA-00933: SQL command not properly ended
Any help or tips would be greatly appreciated as I've been taking SQL for about six weeks and not very proficient!
Thanks!If you really really really want to update the entire table, the syntax would be...
UPDATE book_trans
SET
pastdue_fees = DECODE(SIGN((return_dte - due_dte)*2), -1, 0, 1, 12, Null);I took out all the single quotes. If you actually have a string column and you're storing entirely numbers in it then it should be declared as a NUMBER column and not a character (varchar2) column.
ALWAYS use the proper data type, it'll save you a ton of headaches in the future.
Also, since you're new to the forum, please read the FAQ so you learn the etiquette and what not.
http://wikis.sun.com/display/Forums/Forums+FAQ -
SQL*Loader and DECODE function
Hi All,
I am loading data from data files into oracle tables and while loading the data using SQL*Loader, the following requirement needs to be fulfilled.
1) If OQPR < 300, RB = $ 0-299, SC = "SC1"
2) If 300 < OQPR < 1200, RB = $ 300-1199, SC = "SC2"
3) If 1200 < OQPR < 3000, RB = $ 1200-2999, SC = "SC3"
4) If OQPR > 3000 USD, RB = > $3000, SC = "SC4"
Here OPQR is a field in the data file.
Can anyone suggest how do we handle this using DECODE function? Triggers and PL/SQL functions are not to be used.
TIA.
Regards,
Ravi.The following expression gives you different values for your different intervals and boundaries :
SIGN(:OQPR - 300) + SIGN(:OQPR - 1200) + SIGN(:OQPR - 3000) -
How to use Substring function with Case statement.
Hello Everyone,
I have one requirement where I have to use substring function on the field for report criteria.
E.G.
I have Branch Name Field where I have all branch names information, Now some of the branch names are too big with some extension after the name .
now i want to substing it but the character length varies for each branch.
so is there any way where we can use case statement where we can define that if branch name character are exceeding some value then substing it with this length.Try something like this:
CASE WHEN LENGTH(tablename.Branch_Name) > n THEN SUBSTRING(...) ELSE tablename.Branch_Name END
where n is the number of characters you want to start the break. -
SQL query, Decode function or Case
Hi,
I am writing a procedure, receiving IN parameter p_user_type_cd
where p_user_type possibles values are = 'STUDENT','STAFF','PROVIDER'
if p_user_type_cd = 'STUDENT' , I would like to select WHERE user_type_cd = 'STUDENT'
if p_user_type_cd = 'ALL' , then I would like to select all records. i.e I like to select 'STUDENT','STAFF','PROVIDER'.
SELECT user_type_cd, page_name_cd, access_mode, home_page
FROM oua_user_page_access
WHERE user_type_cd = p_user_type_cd
ORDER BY user_type_cd,home_page;
Will you pl. modify this query to meet the condition.
Thanks,
MuraliHi murali,
I got your situation and its easy to write a decode for the following
WHERE user_type_cd = p_user_type_cdWHERE user_type_cd = decode(:p_user_type_cd, 'STUDENT','STUDENT','STAFF','STAFF','PROVIDER','PROVIDER',
p_user_type_cd)
Here you write the above and you will get the data.
Hope this helps you,
Best Wishes,
Kranthi. -
Decode for this case statement?
case when DES ='TL' or ROLE ='TL' THEN 'PM' ELSE 'PL' end case
May be it does not work with number.
Oracle 10g
SQL*Plus: Release 10.2.0.1.0 - Production on Mon Apr 27 16:26:06 2009
Copyright (c) 1982, 2005, Oracle. All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - 64bit Production
With the Partitioning, OLAP and Data Mining options
SQL> create table test (role number(10), desgn number(10));
Table created.
SQL> insert into test (role,desgn) values (1,100);
1 row created.
SQL> insert into test (role,desgn) values (11,11);
1 row created.
SQL> select decode ('11', to_char(role),'11', to_char(desgn), 'PM', 'TL') from test ;
DE
11
SQL>
Thanks. -
Between function in Case statement
Depending on what the @pintSelectType is equal to I must use either
Clm.InjuryDate BETWEEN @pdteFrom AND @pdteTo
or
Clm.ReceivedDate BETWEEN @pdteFrom AND @pdteTo
but this does not work in the Where clause:
AND
CASE @pintSelectType
WHEN = 1 THEN (Clm.InjuryDate BETWEEN @pdteFrom AND @pdteTo)
ELSE (Clm.ReceivedDate BETWEEN @pdteFrom AND @pdteTo)
END
Please help.Thanks Taherul673. Using your suggestion I ended up with:
AND
(CASE
WHEN @pintSelectType = 1 THEN CONVERT(date, Clm.InjuryDate)
ELSE CONVERT(date, Clm.ReceivedDate)
END) BETWEEN @pdteFrom AND @pdteTo -
Regarding Restrictions on calling functions from sql expressions
Hi all,
While going through the functions of oracle 9i plsql documentation i came across restrictions on calling a function, i that i did not understand the following statement. can anyone explain me with an example. Please.........
Functions called from SQL statements cannot contain statements that end the transactions.
Regards,
Sri Ram.Some where from google
http://www.ucertify.com/article/what-are-the-restrictions-on-a-user-defined-function-that-is-called-from-a-sql-expression.html
>
•The function cannot contain statements that end the transaction. For example, the function cannot contain transaction control statements (such as COMMIT), session control statements (such as SET ROLE), or system control statements (such as ALTER SYSTEM). Also, it cannot contain DDL statements (such as CREATE) because they are followed by an automatic COMMIT. -
I need to know if there is any way to use a range of values from
database and decode to certain text. I am able to do with one
value.
for example:
DECODE(column_name,'216767111','Unlimited',column_name)
above argument works with one value only. How about a range,
ex: 216767000 to 216767111. I need to use only SQL. No PL/SQL.
Kinldly need some body's help
Thanks
MunisWhich version of the database? If it's 8i+ then you can use
the CASE function
for example:
(CASE WHEN column_name between 216767000 and 216767111
THEN 'Unlimited' ELSE column_name END)
This won't work in PL/SQL because they're introducing a CASE
statement does soemthing different.
rgds, APCHello Andrew
Thank you for response. I am using 8i. 8.1.6. However using
CASE, I get inconsistent data type, ORA-00932: inconsistent
datatypes. I able to work it out with other response using
DECODE(sign(. Do you have any idea why i am getting this error.
If time permits, let me know -
CASE Statement error in function -- Please help!
Hi All,
I created a function in my report.
It has a SQL query similar to the one below. The query works fine in SQL plus.
It has a CASE statement. I am getting error at line4 at the select statement. Error is: "Encountered symbol 'SELECT'....."
Can we use CASE statements like this in reports that use SELECT statements for RETURN EXPRESSIONS. Do we have to do any special?
Can someone help me out of this trouble?
THanks in advance.
SELECT PARENT_id,
CASE WHEN EXISTS (SELECT PARENT_id FROM CHILD CH1 WHERE CH1.PARENT_id = PARENT.PARENT_id AND UPPER(CH1.description) LIKE '%ABC%') THEN
(SELECT CH2.MOD_id FROM CHILD CH2 WHERE CH2.PARENT_id = PARENT.PARENT_id AND UPPER(CH2.description) LIKE '%ABC%')
ELSE
(SELECT MOD_id FROM
(SELECT MOD_id,PARENT_id FROM CHILD CH3 ORDER BY started) MOD2 WHERE MOD2.PARENT_id = PARENT.PARENT_id AND ROWNUM = 1
END
) MOD_ID
FROM PARENT;take out the parentheses after the PARENT_ID and see
like below
SELECT parent_id,
CASE
WHEN EXISTS (
SELECT parent_id
FROM CHILD ch1
WHERE ch1.parent_id = PARENT.parent_id
AND UPPER (ch1.description) LIKE '%ABC%')
THEN (SELECT ch2.mod_id
FROM CHILD ch2
WHERE ch2.parent_id = PARENT.parent_id
AND UPPER (ch2.description) LIKE '%ABC%')
ELSE (SELECT mod_id
FROM (SELECT mod_id, parent_id
FROM CHILD ch3
ORDER BY started) mod2
WHERE mod2.parent_id = PARENT.parent_id AND ROWNUM = 1)
END AS mod_id
FROM PARENT; -
Problem with decode function.
Hi,
Can anyone of you help me out in solving this?
It is like i wish to give different select statements according to the value of a parameter entered by user USING DECODE FUNCTION.The select statement contains some other select statements inside it.So when i execute it,it is giving error like 'ORA-00913-too many values(even when i enclose select statements within brackets).ORA-00913 too many values
Cause: The SQL statement requires two sets of values equal in number. This error occurs when the second set contains more items than the first set. For example, the subquery in a WHERE or HAVING clause may return too many columns, or a VALUES or SELECT clause may return more columns than are listed in the INSERT.
Action: Check the number of items in each set and change the SQL statement to make them equal.
the above is from oracle documentation. the brackets is not the problem, u must be using multiple items in the integrated decode queries. If the problem still exists post ur DML for further analysis.
zaibi. -
Hello,
This is relating to one of the previous posts.
CASE STATEMENT PERFORMANCE
As it has been a discussion of case statement performance. I tried to compare both the filter function and case statement.
they both actually generate the same physical query.
So I just am trying to understand the difference.
thanks,
DeepHi Deep,
There would be some performance using CASE where as filter function would generate straight SQL that is WHERE clause is added into the SQL statement for better performance.
Have a look at this http://www.biconsultinggroup.com/obiee-tips-and-tricks/using-a-filter-function-instead-of-case-statements.html
http://prolynxuk.com/blog/?p=462
UPDATED POST
Can you paste both SQL's generated here.
hope answered
Cheers,
KK
Edited by: Kranthi.K on Apr 22, 2011 7:33 PM -
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.
Maybe you are looking for
-
Deleting data from a table view
I have a data source that is in dictionary form (for why, see here). I have the following code that gets called in the commitEditing method for the table view: - (void)removeObjectFromListAtIndex:(NSIndexPath *)indexPath { NSMutableDictionary *mutabl
-
Web service error while consuming
i have created a webservice and needed to check it so i tried to consume this web service with the wsdl i generated but its throwing an error can anybody tell me how to slove the problem, <?xml version="1.0" encoding="utf-8" ?> - <asx:abap xmlns:
-
How to set focus on a custom PO Item screen field when in error?
Hi All, I have an interesting situation that i'm wondering if others have solved. We have extended the PO item table (EKPO) by adding two new fields. We then have implemented two BAdI's: ME_GUI_PO_CUST and ME_PROCESS_PO_CUST to add them to the ME2
-
Hi, I'm currently having problems embedding a flash movie into a powerpoint presentation, using steps similar to the ones set out at this link: http://www.flashgeek.com/tutorials/02_embed_01.asp The flash movie will play perfectly until the presentat
-
ITunes unexpectantly crashes on iPad.
iTunes crashes while shopping. Never had a problem before this week and iTunes is the only app that's crashing on my iPad. Any ideas as to why this is happening?