Case statement in Oracle 8i
can anyone tell me what to do to make the query below run in Oracle 8i.
thanks
select
case connum
when 'C251234' then 'Good'
when 'C318260' then 'Ok'
else connum end
from names
I believe the confusion arises since CASE and other new functions and features in 8i - analytic functions, NVL2 scalar subquery ..., did not work in PL/SQL in 8i due to it having a different SQL parsing engine. A common work around was to put the offending SQL in a view or execute it as dynamic SQL where PL/SQL would use the database parser.
SQL> select
2 case when connum = 'C251234' then 'Good'
3 when connum = 'C318260' then 'Ok'
4 else connum end
5 from (
6 select 'AAAA' connum from dual
7 union all
8 select 'C251234' from dual
9 union all
10 select 'C318260' from dual
11 );
CASEWHE
AAAA
Good
Ok
SQL> var c refcursor
SQL> begin
2 open :c for
3 select
4 case when connum = 'C251234' then 'Good'
5 when connum = 'C318260' then 'Ok'
6 else connum end
7 from (
8 select 'AAAA' connum from dual
9 union all
10 select 'C251234' from dual
11 union all
12 select 'C318260' from dual
13 );
14 end;
15 /
case when connum = 'C251234' then 'Good'
ERROR at line 4:
ORA-06550: line 4, column 1:
PLS-00103: Encountered the symbol "CASE" when expecting one of the following:
( * - + all mod null <an identifier>
<a double-quoted delimited-identifier> <a bind variable>
table avg count current distinct max min prior sql stddev sum
unique variance execute the forall time timestamp interval
date <a string literal with character set specification>
<a number> <a single-quoted SQL string>
SQL> var c refcursor
SQL> begin
2 open :c for
3 'select
4 case when connum = ''C251234'' then ''Good''
5 when connum = ''C318260'' then ''Ok''
6 else connum end
7 from (
8 select ''AAAA'' connum from dual
9 union all
10 select ''C251234'' from dual
11 union all
12 select ''C318260'' from dual
13 )';
14 end;
15 /
PL/SQL procedure successfully completed.
SQL> print c
CASEWHE
AAAA
Good
Ok
SQL> select * from v$version where rownum = 1;
BANNER
Oracle8i Enterprise Edition Release 8.1.7.4.0 - Production
Similar Messages
-
Case Statement in Oracle Query.
Hello Oracle Gurus,
I need suggestion on whether I should use Case statement in Oracle queries.
I have a sql statement which inserts the data by selecting data from other table. While selecting the data I have put a logic in the select statement for one column which is something like this and there are some more similar statements in the same query.
CASE
WHEN (b.ACCOUNT = 'FIN' or b.ACCOUNT ='FIN ACC' or b.ACCOUNT like '%Global Eq%' or b.ACCOUNT like '%Flexible Bond%')
THEN
'MTM'
WHEN (substr(a.CTC,-3)='MTM')
THEN
'MTM'
WHEN (substr(a.CTC,-3)='AFS' or substr(a.CTC,-3)='HTM' OR substr(a.CTC,-3)='ACC' OR substr(a.CTC,-3)='HFI' )
THEN
'ACC'
ELSE
'OTH'
END,
I wanted to get an suggestion about how much performance issue can I have due to this in my insert statement.
Let me know if you need any other information.All comments are really appreciated.Hi,
It's depends on the joins how you have performed with source table, stats and existing of indexes. If the volume of data is high - in case of any performance issue - why can't you perform the required things of logical conditions of data and popualte in one cluster so - that you can fetch out the chunks of required information with better way and in support with indexes.
Let us know the ful query your working on
Oracle version
Explain plans - get it from dbms_xplan.
- Pavan Kumar N
- ORACLE - 9i/10g - OCP
RHCE - Enterprize Linux 5.4 -
CASE statement in Oracle 8i PL/SQL
I'm in the process of doing an upgrade from 8i to 10g and have the necessary instructions in performing it. however, after running the pre upgrade tasks (run utlu102i.sql) to show the preupgrade information, i found out that there are some INVALID objects.
Miscellaneous Warnings
WARNING: --> Database contains INVALID objects prior to upgrade.
.... USER INGITRN has 1 INVALID objects.
.... USER INGIUAT has 3 INVALID objects.
.... USER OEMMON has 7 INVALID objects.
.... USER RE_ITF_USER has 11 INVALID objects.
.... USER SYS has 1 INVALID objects.
Would it be ok to proceed with the upgrade and ignore the warnings?
Also, as i checked the invalid object for SYS, it shows:
OWNER OBJECT_NAME OBJECT_TYPE STATUS
SYS UTL_RECOMP PACKAGE VALID
SYS UTL_RECOMP PACKAGE BODY INVALID
Further more, i tried to do a fix by invoking utlirp.sql and the same objects are showing up. Same thing shows when invoking utlrp.sql or even doing a manual compile for the affected objects. I later found out that CASE statements are not accepted in PL/SQL for Oracle 8i.
Can you help me fixed the issue on the invalid object?
ThanksHi,
Try first to (re)compile ll invalid objects. then
you can run:
select owner,type,count(*) from all_errors
group by owner,typeif you still have uncompiled objects, then report the different errors:
select * from all_errors... -
Just a FYI regarding Case statements in ORacle 8i in pl/sql
Well..I saw numerous posts in this forum regarding not being able to do case statement within pl/sql. Well..you can do
that using dynamic SQL. IT works like a champ.Hi,
Try first to (re)compile ll invalid objects. then
you can run:
select owner,type,count(*) from all_errors
group by owner,typeif you still have uncompiled objects, then report the different errors:
select * from all_errors... -
Got error when use case statement in oracle stored procedure
Hi,
I have a query like:
select merchant_id,
case
when product_type='K' then 'Production'
when product_carrier='UC' THEN 'Shipping'
end the_type
from product_tbl
where merchant_id=10114
It works fine. But as soon as I put it into a stored procedure, I got error like:
Encountered the symbol "CASE" when expecting one of the following:
( - + mod null <an identifier>
Please help!Oracle 8i doesn't support CASE into PL/SQL, so as Kamal said, create a view with the CASE, and use this view into your PL/SQL.
Nicolas.
And an example here :
Re: Execute Immediate doesnot work in 8i (8.1.7) and Ref Cursor not exec qu
Sorry Kamal.
Message was edited by:
N. Gasparotto -
Need help converting Excel IF statement into CASE WHEN statement for Oracle
Hi,
Hope someone can help I have tried various ways of getting this to work, to no avail!
Bascially I have some figures that are minus figures, and I need to add them together to get a movement figure, but I need to treat the minus figures as minus, if that makes sense, rather than the usual... a minus and a minus makes a plus.
For example:- Budget Figure = -1% and Actual Figure = -68% so the movement needs to be -69%.
The IF statement I have been using in Excel is the following:-
=IF(FO110<0,(FP110-(IF(FO110=0,1,FO110)*-1)),FP110-IF(FO110=0,1,FO110))
Which when using the figures as above = -69%
Cell FO = The Budget Figure
Cell FP = The Actual Figure
However, when I created the CASE statement in Oracle, the figure in the query comes back as -0.67, which is oviously not what I want to happen when both actual and budget are minus figures; however when they are a minus and a plus, it works perfectly fine.
Any help on this would be most appreciated!
Kind regards,
AnnmarieHappy I did'n mess something up :)
Nevertheless, don't show it too much around because
case when budget < 0
then actual - case when budget = 0 /* will never happen */
then 1 /* will never happen */
else budget
end * (-1) /* -budget * (-1) remains only */
else actual - case when budget = 0
then 1
else budget
end
endso at least try the following (if case is more readable as decode for you). Let's hope it works as I don't have a Database at hand
case when budget < 0
then actual + budget
else actual - case when budget = 0
then 1
else budget
end
end Regards
Etbin -
Case statement problems in oracle forms 6i
Hello,
Any one can help me that how to use case statment in Oracle forms 6i.
i have read one thread and there was no proper solution so could any one please let me know to use case statement.
Please also let me know which category i should search for FORMS 6i.
when i'm using below code with cursor then i'm getting error 103
database:=11g
application := forms 6i
operating system:= win Xp
code is given below :-
cursor c1 is
select nc.nomenclature_id,
nvl(nc.category_value, 0) master,
nvl(nc2.category_value, 0) case,
nvl(nc3.category_value, 0) bundle,
case
when nvl(nc.category_value, 0) > 0 and
nvl(nc2.category_value, 0) > 0 and
nvl(nc3.category_value, 0) > 0 then
'A' --All packouts Master, Case, Bundle
when nvl(nc.category_value, 0) > 0 and
nvl(nc2.category_value, 0) > 0 and
nvl(nc3.category_value, 0) = 0 then
'B' --Both Master and Case
when nvl(nc2.category_value, 0) = 0 and
nvl(nc3.category_value, 0) = 0 then
'C' --Master Case Only
else
'N'
end code
from nomn_category nc, --master case
(select nc2.nomenclature_id,
nc2.category_value
from nomn_category nc2
where nc2.category_id = '230732') nc2,
(select nc3.nomenclature_id,
nc3.category_value
from nomn_category nc3
where nc3.category_id = '236566') nc3
Edited by: Rahul on Feb 3, 2012 7:18 PM
Edited by: Rahul on Feb 3, 2012 7:20 PMhello Andreas,
It is ok but i dont have to use view there.
i need to use without view, because this code has to be use in FORMS6i.
But Forms6i doesn't support to case function. i'm newbie in Forms.
If you can convert to below bold one portion(case) into decode then please help me or
if you have any idea about Forms6i then please send me any link where is given explanation about excel report that how to make excel report through Forms6i step by step and that excel report should be generate on any dynamic path which is given by user:-
cursor c1 is
select nc.nomenclature_id,
nvl(nc.category_value, 0) master,
nvl(nc2.category_value, 0) case,
nvl(nc3.category_value, 0) bundle,
case
when nvl(nc.category_value, 0) > 0 and
nvl(nc2.category_value, 0) > 0 and
nvl(nc3.category_value, 0) > 0 then
*'A'*
when nvl(nc.category_value, 0) > 0 and
nvl(nc2.category_value, 0) > 0 and
nvl(nc3.category_value, 0) = 0 then
*'B' --Both Master and Case*
when nvl(nc2.category_value, 0) = 0 and
nvl(nc3.category_value, 0) = 0 then
*'C'*
else
*'N'*
end "code"
from nomn_category nc,
(select nc2.nomenclature_id,
nc2.category_value
from nomn_category nc2
where nc2.category_id = '230732') nc2,
(select nc3.nomenclature_id,
nc3.category_value
from nomn_category nc3
where nc3.category_id = '236566') nc3
thanks -
[Oracle 8i] Handling null in case statement
The following bit of my query is causing the error 'inconsistent datatypes':
CASE
WHEN b.days_diff < 0
THEN plan_start
ELSE plan_start + b.days_diff
ENDThe problem is that b.days_diff can be null.
I've tried to work around this, by using the NVL statement and by nesting 2 case statements to try to deal with the null, but can't seem to work around it.
Does anyone have anything else I can try?Apologies...internet server went down yesterday...
I've had this issue before with my database. When I look at user_tab_columns, it says plan_start is a date. However, I have had to use TO_DATE in the past with it to get some things to work. It's very odd, and I have no idea why it's like that.
Anyway, below, I have provided some sample data, and the full query I'm trying to run:
CREATE TABLE ord (
ord_nbr char(10)
ord_stat char(2)
INSERT INTO ord
VALUES ('0000012345', 'OP');
INSERT INTO ord
VALUES ('0000012346', 'OP');
INSERT INTO ord
VALUES ('0000012347', 'CL');
INSERT INTO ord
VALUES ('0000012348', 'OP');
CREATE TABLE op (
ord_nbr char(10)
operation char(4)
op_status char(2)
plan_start date
pln_due date
dt_complete date
INSERT INTO op
VALUES ('0000012345', '0001', 'CL', {ts '2009-01-01 00:00:00'}, {ts '2009-01-02 00:00:00'}, {ts '2009-01-04 00:00:00'});
INSERT INTO op
VALUES ('0000012345', '0002', 'CL', {ts '2009-01-02 00:00:00'}, {ts '2009-01-03 00:00:00'}, {ts '2009-01-06 00:00:00'});
INSERT INTO op
VALUES ('0000012345', '0003', 'CL', {ts '2009-01-03 00:00:00'}, {ts '2009-01-04 00:00:00'}, {ts '2009-01-09 00:00:00'});
INSERT INTO op
VALUES ('0000012345', '0004', 'WK', {ts '2009-01-04 00:00:00'}, {ts '2009-01-05 00:00:00'}, {ts '1900-12-31 00:00:00'});
INSERT INTO op
VALUES ('0000012345', '0005', 'OP', {ts '2009-01-05 00:00:00'}, {ts '2009-01-06 00:00:00'}, {ts '2009-01-02 00:00:00'});
INSERT INTO op
VALUES ('0000012346', '0001', 'CL', {ts '2009-01-01 00:00:00'}, {ts '2009-01-02 00:00:00'}, {ts '2009-01-01 00:00:00'});
INSERT INTO op
VALUES ('0000012346', '0002', 'OP', {ts '2009-01-02 00:00:00'}, {ts '2009-01-04 00:00:00'}, {ts '1900-12-31 00:00:00'});
INSERT INTO op
VALUES ('0000012346', '0003', 'OP', {ts '2009-01-04 00:00:00'}, {ts '2009-01-06 00:00:00'}, {ts '1900-12-31 00:00:00'});
INSERT INTO op
VALUES ('0000012347', '0001', 'CL', {ts '2009-01-01 00:00:00'}, {ts '2009-01-02 00:00:00'}, {ts '2009-01-03 00:00:00'});
INSERT INTO op
VALUES ('0000012347', '0002', 'CL', {ts '2009-01-02 00:00:00'}, {ts '2009-01-05 00:00:00'}, {ts '2009-01-06 00:00:00'});
INSERT INTO op
VALUES ('0000012348', '0001', 'OP', {ts '2009-01-15 00:00:00'}, {ts '2009-01-17 00:00:00'}, {ts '1900-12-31 00:00:00'});
INSERT INTO op
VALUES ('0000012348', '0002', 'OP', {ts '2009-01-17 00:00:00'}, {ts '2009-01-20 00:00:00'}, {ts '1900-12-31 00:00:00'});Full query:
SELECT ord.ord_nbr
, ord.ord_stat
, op.operation
, op.op_status
, op.plan_start
, //where I want to return plan_start + days_diff if days_diff is not null or negative
//otherwise, I want to return just plan_start
AS adjusted_start
, op.dt_complete
, b.max_cl_op
, b.pln_due
, b.dt_complete
, b.days_diff
FROM ord
, op
SELECT a.ord_nbr
, a.max_cl_op
, op.pln_due
, op.dt_complete
, (op.dt_complete-op.pln_due) AS days_diff
FROM (
SELECT op.ord_nbr
, MAX(TO_NUMBER(op.operation)) AS max_cl_op
FROM ord
, op
WHERE ord.ord_nbr = op.ord_nbr
AND ord.ord_stat != 'CL'
AND op.op_status ='CL'
GROUP BY op.ord_nbr
) a
WHERE op.ord_nbr = a.ord_nbr
AND op.operation = a.max_cl_op
) b
WHERE ord.ord_nbr = op.ord_nbr
AND op.ord_nbr = b.ord_nbr (+)
AND ord.ord_stat != 'CL'
AND op.op_status != 'CL'
AND op.plan_start <= ADD_MONTHS(sysdate, 12)The results I want to get:
ord.ord_nbr ord.ord_stat op.operation op.op_status op.plan_start adjusted_start op.dt_complete b.max_cl_op b.pln_due b.dt_complete b.days_diff
'0000012345' 'OP' '0004' 'WK' 1/4/2009 1/9/2009 12/31/1900 '0003' 1/4/2009 1/9/2009 5
'0000012345' 'OP' '0005' 'OP' 1/5/2009 1/10/2009 12/31/1900 '0003' 1/4/2009 1/9/2009 5
'0000012346' 'OP' '0002' 'OP' 1/2/2009 1/2/2009 12/31/1900 '0001' 1/2/2009 1/1/2009 -1
'0000012346' 'OP' '0003' 'OP' 1/4/2009 1/4/2009 12/31/1900 '0001' 1/2/2009 1/1/2009 -1
'0000012348' 'OP' '0001' 'OP' 1/15/2009 1/15/2009 12/31/1900
'0000012348' 'OP' '0002' 'OP' 1/17/2009 1/17/2009 12/31/1900 -
Hi all,
I have to compare the value of a varchar variable using a CASE statement and display the corresponding output.
But when the following code is being executed, and i gave the value of dayrange as anything other than number, i am getting the error;
The daysrange variable can be a number or a string (Hence i declared it as a varcahr2)
Error report:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 5
06502. 00000 - "PL/SQL: numeric or value error%s"
*Cause:
*Action:
declare
daysrange varchar2(10):='abc';
x varchar2(100);
begin
CASE WHEN DAYSRANGE = 1 THEN x := 'LD';
WHEN DAYSRANGE BETWEEN 2 AND 7 THEN x := 'LW';
WHEN DAYSRANGE BETWEEN 8 AND 30 THEN x:= 'LM';
WHEN DAYSRANGE BETWEEN 31 AND 90 THEN x:= 'L3M';
WHEN DAYSRANGE BETWEEN 91 AND 180 THEN x:= 'L6M';
WHEN DAYSRANGE BETWEEN 181 AND 365 THEN x:= 'LY';
WHEN DAYSRANGE BETWEEN 366 AND 730 THEN x:= 'L2Y';
WHEN DAYSRANGE > 730 THEN x:= 'O2Y';
ELSE x:='x:= x';
END case;--DATERANGE
exception
when case_not_found then
x:='something';
dbms_output.put_line(x);
end;
Edited by: Chaitanya on Nov 25, 2010 1:25 AMHi,
Chaitanya wrote:
... The daysrange variable can be a number or a string (Hence i declared it as a varcahr2)That's usually not a good design. It would be better to have two variables (or columns) if necessary, a VARCHAR2 and a NUMBER.
If you can't change the design, then test daysrange, and then do different things depending on whether it is a number or not.
For example:
declare
daysrange varchar2(10) := '17';
daysrange_n NUMBER;
x varchar2(100);
begin
IF REGEXP_LIKE (daysrange, '^\d+$')
THEN
daysrange_n := TO_NUMBER (daysrange);
x := CASE
WHEN daysrange_n > 730 THEN 'O2Y'
WHEN daysrange_n > 365 THEN 'L2Y'
WHEN daysrange_n > 180 THEN 'L1Y'
WHEN daysrange_n > 90 THEN 'L6M'
WHEN daysrange_n > 30 THEN 'L3M'
WHEN daysrange_n > 7 THEN 'LM'
WHEN daysrange_n > 1 THEN 'LW'
WHEN daysrange_n = 1 THEN 'LD'
ELSE x -- If necessary
END;
END IF;
...The tests in a CASE expression are done in order. The n-th WHEN condition is tried only after conditions 1 through n have failed. That's why we can saY, for example,
"daysrange_n > 365" instead of
"daysrange_n BETWEEN 366 AND 730". If the 2nd test is even being performed, we know that the 1st test failed, and that daysrnage_n is not > 730.
I'm not saying that you have to write CASE expressions like this, or that it's necessarily better. You should know that it's possible, then choose whichever way makes the most sense in this situation. -
CASE not found while executing CASE statement on Submit Form
Hi to all APEX users and developers.
I have several APEX applications and they are all working well, but recently I got one strange exception when I try to submit page:
Session: Fetch session header information
...metadata, fetch page info
...Validate item page affinity.
...Validate hidden_protected items.
Add error onto error stack
...Error data:
......message: Error processing request.
......additional_info: ORA-06592: CASE not found while executing CASE statement
......display_location: ON_ERROR_PAGE
......is_internal_error: true
......apex_error_code: APEX.UNHANDLED_ERROR
......ora_sqlcode: -6592
......ora_sqlerrm: ORA-06592: CASE not found while executing CASE statement
.....error_backtrace: ORA-06512: at "APEX_040100.WWV_FLOW", line 9273
......component.type: APEX_APPLICATION_AUTH
......component.id: 41350431648668800
......component.name: MNRFR
...Show Error on Error Page
......Performing rollback
Processes - point: AFTER_ERROR_HEADER
Processes - point: BEFORE_ERROR_FOOTER
End Page Processinga
Page has more than 120 items (most of them are hidden), so my first thought is that page has problem with posting so many items, but APEX error message doesn't hel me at all. Any help would be very appreciated :)
AlmirHi Almir,
actually it is the 100 page item limit. See (http://download.oracle.com/docs/cd/E17556_01/doc/user.40/e15517/limits.htm)
I also had a look into the source code and the code at the position where the error gets raised only supports 100 page items.
Can you have a look into the generated HTML code and look if you have a page items which is mapped to p_t101 or a higher number ?
I will file a bug to show a better error message.
Regards
Patrick
My Blog: http://www.inside-oracle-apex.com
APEX Plug-Ins: http://apex.oracle.com/plugins
Twitter: http://www.twitter.com/patrickwolf -
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. -
More than one variable at a time in case statement
hi i am using oracle 10g database.
can it be possible ?
in if condition we can have more than one variable in one condition
if a=100 then
b:=200;
c:=300;
end if;
how it will be in case statement ? i have searched lot on internet but didnt get
case
when a=100 then 200, 300 ... ???
thanksHi FRNzzz!! wrote:
hi i am using oracle 10g database.
can it be possible ?
in if condition we can have more than one variable in one condition
if a=100 then
b:=200;
c:=300;
end if; how it will be in case statement ? i have searched lot on internet but didnt get
case
when a=100 then 200, 300 ... ???
thanksnot sure if I got your question correctly, is this what you are looking for?
SQL> ed
Wrote file afiedt.buf
1 declare
2 a number := 100;
3 b number;
4 c number;
5 begin
6 case
7 when a = 100 then
8 b := 200;
9 c := 300;
10 when a = 0 then
11 b := 300;
12 c := 400;
13 else
14 b := 0;
15 c := 0;
16 end case;
17 dbms_output.put_line('a :'||a||' b :'||b||' c :'||c);
18* end;
SQL> /
a :100 b :200 c :300
PL/SQL procedure successfully completed. -
Please help: Case Statement - ORA-01722: invalid number Error
Hi All,
I'm trying to use Case statement to recode Cancelled statuses into two groups
'Reject' if the difference between first date and last date is less than 29 and
'Accept' if the difference between first date and last date is greater than 30
Here is my 'test' data:
STATUS FIRST_DATE LAST_DATE
Transfer 10/08/2011 10/09/2011
Mover 10/08/2011 15/09/2011
Cancel 10/08/2011 16/09/2011
Cancel 10/08/2011 5/09/2011
Here is the syntax
select a.*,
(CASE WHEN a.STATUS ='Cancel' THEN (round(a.LAST_DATE-a.FIRST_DATE))
ELSE 0
END) CAN_DAYS,
(CASE WHEN 'CAN_DAYS' >29 THEN 'Reject'
WHEN 'CAN_DAYS' <30 THEN 'Accept'
END) Reject_Accept
from test a
The first CASE statement works fine and gives me this
STATUS FIRST_DATE LAST_DATE CAN_DAYS
Transfer 10/08/2011 10/09/2011 0
Mover 10/08/2011 15/09/2011 0
Cancel 10/08/2011 16/09/2011 37
Cancel 10/08/2011 5/09/2011 26
but the second CASE produces ORA-01722: invalid number Error. It is something to do with the CAN_DAYS data type, Oracle doesn't see it as Numeric i think.
The result i want to see would be
STATUS FIRST_DATE LAST_DATE CAN_DAYS Reject_Accept
Transfer 10/08/2011 10/09/2011 0
Mover 10/08/2011 15/09/2011 0
Cancel 10/08/2011 16/09/2011 37 Accept
Cancel 10/08/2011 5/09/2011 26 Reject
Could someone please help me to fix the syntax?
Thank you in advance,This seems to give you your desired results...
with test as
( select 'Transfer' as status, to_date('10/08/2011') as first_date, to_date('10/09/2011') as last_date from dual union all
select 'Mover' , to_date('10/08/2011') , to_date('15/09/2011') from dual union all
select 'Cancel' , to_date('10/08/2011') , to_date('16/09/2011') from dual union all
select 'Cancel' , to_date('10/08/2011') , to_date('05/09/2011') from dual
select status
, first_date
, last_date
, CAN_DAYS
, CASE
WHEN CAN_DAYS = 0 THEN NULL
WHEN CAN_DAYS < 30 THEN 'Reject'
WHEN CAN_DAYS >= 30 THEN 'Accept'
END Reject_Accept
from ( select status
, first_date
, last_date
, CASE
WHEN STATUS ='Cancel' THEN round(LAST_DATE-FIRST_DATE)
ELSE 0
END CAN_DAYS
from test
; -
Adding a field to an sql statement in Oracle Reports error ORA-00933
We have been requested to add a field that already exists in the table referred to by the sql statement in Oracle Reports Builder. The report was set up by a consultant about 3 yrs ago and we don't really have much skill in this area. What is happening when I try to modify the SQL statement, either adding a field or deleting a field to the SELECT statement, causes an error message preventing the statement from being saved. The only way out of the error message is to click Cancel. The error message is
ORA-00933:SQL command not properly ended
ORDER BY Program ==> NAME
Even adding or deleting a space anywhere in the SQL statement causes the error (not adding any new fields). A coworker found that if we comment out the ORDER BY, the statement will accept the new field in the SELECT section, however then we lose the order by functionality. I would like to add one additional field before the FROM. Not sure if any additional data are needed. Thank you.
SELECT p.person_uid PIDM_KEY, p.id_number ID,
p.full_name_lfmi name,
p.BIRTH_DATE, p.GENDER Sex,
Decode(a.residency,'D',p.Primary_ethnicity,'F') Ethn,
a.academic_period TERM,
CASE WHEN :p_group_by = 'PROGRAM' THEN a.program
ELSE ' '
END AS Program,
a.COLLEGE, a.degree, a.major, ' ' rule,
a.STUDENT_POPULATION,a.STUDENT_LEVEL, a.application_status Status, a.application_status_date app_sts_dte,
ad.decision_date1 Last_Dec_Date,
ad.decision1||' '||ad.decision2||' '|| ad.decision3||' '|| ad.decision4||' '|| ad.decision5 Decisions,
/* Deposit Date uses the last term entered in :p_term parameter string */
(SELECT MAX(deposit_effective_date) FROM usf_as_deposit WHERE account_uid = a.person_uid &term_clause group by account_uid) AS "DEPOSIT DATE",
ph.phone as PHONE,
CASE WHEN PS.FIRST_CONTACT IN ('NET','PAP','COM','COP') THEN PS.First_Contact
ELSE CASE WHEN ps.latest_contact IN ('NET','PAP','COM','COP') THEN PS.Latest_Contact
ELSE ' '
END
END AS FIRST_CONTACT,
DECODE(:p_address,'Y',REPLACE(adr.street1||' '||adr.street2||' '||adr.street3||' '||adr.city||','||adr.state||' '||adr.nation||' '||adr.zip,' ',' '),' ') as address, adr.nation, adr.state,
goremal_email_address email, a.residency, a.application_date, p.primary_ethnicity, c.cohort
FROM MST_ADMISSIONS_APPLICATION A,
MST_PERSON p,mst_pre_student PS, Admissions_Cohort c, usf_v_phone_pr_ma ph,
MST_admissions_decision_slot AD, usf_v_email, usf_v_address_dr_lr_ma_pr adr
WHERE a.PERSON_UID = p.person_uid
AND a.curriculum_priority = 1
AND a.person_uid = ps.person_uid
AND a.person_uid = ad.person_Uid(+)
AND a.person_uid = goremal_pidm(+)
AND a.person_uid = adr.pidm(+)
AND a.person_uid = ph.pidm(+)
AND ph.rnum(+) = 1
AND a.person_uid = c.person_uid(+)
AND a.academic_period = c.academic_period(+)
&Where_Clause
/* TAKE OUT FOLLOWING LINE AFTER DATA IS CLEANED UP */
AND NOT(p.id_number = '00000000' OR SUBSTR(p.id_number,1,1) = 'B' OR UPPER(p.full_name_lfmi) LIKE '%TESTING%')
AND a.application_status_date >= NVL(:p_as_of_date,sysdate-8000)
AND a.academic_period = ad.academic_period(+)
AND a.application_number = ad.application_number(+)
AND a.degree <> 'ND' /* AND a.college <> 'LW' -- Does not need non-degree and law students */
&Cohort_Clause
ORDER BY Program &ORDER_CLAUSEHi Denis,
I tried your suggestion. The good thing is that adding the comma allowed me to be able to add a.campus to the select statement, unfortunately, another error message happened.
ORA-00936: missing expression SELECT p . person_uid PIDM_KEY ,
p . id_number , p . full_name_lfmi name , p . BIRTH_DATE , p . GENDER Sex ,
Decode ( a . residency , 'D' , p . Primary_Ethnicity , 'F' ) Ethn , a . academic_period TERM ,
CASE WHEN : P_group_by = 'PROGRAM THEN a I started over and tried only putting in the comma and get the same message even though I didn't add campus. After that, removed the comma which led to the ORA-00933 error message. So once again, I had to close the file without saving, in order for the report to run at all. -
CASE Statement is not working Derived table
Hi All,
in the bello SQL Statement case statement is not working in derived table. I am new to creation of derived table if any body knows plz kinldy help me out on this.
SELECT x.market, x.droprate as med1
FROM
(select upper(market_name) as market, fulldate as date_value,
(sum([Dy_LOT_DROPS_N][Dy_OB_HO_DROPS][Dy_NonRF_Drop]))/
nullif(sum(CASE WHEN (month(BBHDLY.FullDate)}>= 6 and { year(BBHDLY.FullDate)} = 2011) or {fn year(IDENSLABBHDLY.FullDate)} > 2011
THEN BBHDLY.Dy_Calls - BBHDLY.Dy_HO_CHAN_ALLOC ELSE BBHDLY.Dy_Calls END),0)*100 as droprate
from BBHDLY sla
inner join Dim mkt
on sla.bts_name = mkt.bts_name and sla.SectorID = mkt.Sector_Id
where fulldate >= GETDATE()-46
group by market_name, fulldate) x,
(select market_name as market, fulldate as date_value,
(sum([Dy_LOT_DROPS_N][Dy_OB_HO_DROPS][Dy_NonRF_Drop]))/
nullif(sum(CASE WHEN ({fn month(BBHDLY.FullDate)}>= 6 and {fn year(BBHDLY.FullDate)} = 2011) or {fn year(BBHDLY.FullDate)} >
2011 THEN BBHDLY.Dy_Calls - BBHDLY.Dy_HO_CHAN_ALLOC ELSE BBHDLY.Dy_Calls END),0)*100 as droprate
from BBHDLY sla
inner join Dim mkt
on sla.bts_name = mkt.bts_name and sla.SectorID = mkt.Sector_Id
where fulldate >=GETDATE()-46
group by market_name, fulldate) y
where x.market = y.market
GROUP BY x.droprate, x.market
HAVING
SUM(CASE WHEN y.droprate <= x.droprate
THEN 1 ELSE 0 END)>=(COUNT(*)+1)/2 AND
SUM(CASE WHEN y.droprate >= x.droprate
THEN 1 ELSE 0 END)>=(COUNT(*)/2)+1
ThanksIt looks like SQL Server or Sybase given that you're using getdate().
As such, Vinesh's comment to use decode is wrong - decode is Oracle syntax.
Looking at your statement again, I've noticed the following:
you have no { to match the first } - not sure why you're using them anyway.
you haven't given x.market a name - use x.market as market instead
use coalesce instead of nullif if you're on SQL Server.
Maybe you are looking for
-
Why is the URL constantly updated in ie but not in safari?
Safari: https://www.mysite.com/app/editor?handle_type_id=7#m=editor&wfs=2 Internet Explorer 8: https://www.mysite.com/app/editor?handle_type_id=7#1262397566?1262397566?1262397566?126239 7566?1262397566?1262397566?1262397566?1262397566?1262397566?1262
-
I've got an iCloud notification that I can't get rid of
I plugged it in and it gives the Not Enough Storage notification where you can click "close" or "settings". When I tried to click either, it didn't work. So I left it and went to sleep and woke up with the same message still there on the screen I can
-
Netflix pausing for no apparent reason
Hello, I have a 27" imac purchased in Jan 2014. Chose max CPU, RAM, graphics card, etc. I have one problem that I can't pin down. While watching netflix, only on HD movies, the movie pauses for a second or maybe two seconds every minute or so. Ap
-
Is it possible to use ddr2-533 memory in Satellite M40-101 ?
now in my notebook is installed 512Mb ddr pc2700. i want to upgrade to 1Gb. is it possible to use ddr2-533 in this notebook?
-
How do I import a picture in a video?
Hi, When I drag the picture into the video the picture in video option does not appear. What else can I do?