CASE Expression question
Hi,
I am wondering how to implement case logic where THEN statement would be written only once for many WHEN's.
This example is from the oracle documentation, I extended it a bit.
SELECT cust_last_name,
CASE credit_limit
WHEN 100 THEN 'Low'
WHEN 200 THEN 'Low'
WHEN 5000 THEN 'High'
ELSE 'Medium'
END
FROM customers;
As you see we select 'Low' for both values 100 and 200.
What I am really looking for is something like:
SELECT cust_last_name,
CASE credit_limit
WHEN 100
WHEN 200 THEN 'Low'
WHEN 5000 THEN 'High'
ELSE 'Medium'
END
FROM customers;
OR
SELECT cust_last_name,
CASE credit_limit
WHEN 100 OR 200
THEN 'Low'
WHEN 5000 THEN 'High'
ELSE 'Medium'
END
FROM customers;
But both of selects are not valid in oracle (tested on 10g Rel2)
Maybe it is very simple and I am witting it wrong, or it is working only the way I have to repeat the THEN to every WHEN.
Thanks in advance!
let's say I would like to perform the same step
Hello
What about
tylerd@DEV2> SELECT
2 CASE
3 WHEN dummy IN('X','Y','Z') THEN
4 'Dummy is X, Y or Z'
5 WHEN dummy LIKE 'A%' THEN
6 'Dummy is like A'
7 ELSE
8 'Dummy is something else'
9 END
10 FROM
11 dual
12 /
CASEWHENDUMMYIN('X','Y'
Dummy is X, Y or ZTHTH
David
Similar Messages
-
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 -
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) -
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 -
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. -
Nested CASE expressions in SQL Server 2008 R2
Hi, For some reason when I use the below CASE expression in my SELECT statement I get duplicate records.
CASE WHEN <Condition 1> THEN <Expression 1>
WHEN <Condition 2> THEN <Expression 2>
WHEN <Condition 3> THEN <Expression 3>
WHEN <Condition 4> THEN <Expression 4>
END AS CaseResult
Also tried using coalesce with no luck. How to write a nested CASE expression which would yield just one expression. In case if I have to combine 2 different Expressions for 1 record, Is there a way to merge the 2 Expressions writing CASE
expression something like below.
STUFF ((SELECT ',' + CASE WHEN <Condition 1> THEN <Expression 1>
WHEN <Condition 2> THEN <Expression 2>
WHEN <Condition 3> THEN <Expression 3>
WHEN <Condition 4> THEN <Expression 4>
END
FOR XML PATH(''), ROOT('MyString'), TYPE).value('/MyString[1]','VARCHAR(MAX)'), 1, 1,'') AS CaseResult
--ResultSet
CaseResult
<Expression 1, Expression 2>
I am using SQL Server 2008 R2. Thanks in advance.......
IoneHi, For some reason when I use the below CASE expression in my SELECT statement I get duplicate records. Also tried using coalesce with no luck. How to write a nested CASE expression which would yeild just one expression. In case if I have to combine 2 different
Expressions for 1 record, Is there a way to merge the 2 Expressions writing CASE expression something like below in SQL Server 2008 R2.
CASE WHEN <Condition 1> THEN <Expression 1>
WHEN <Condition 2> THEN <Expression 2>
WHEN <Condition 3> THEN <Expression 3>
WHEN <Condition 4> THEN <Expression 4>
END AS CaseResultSTUFF ((SELECT ',' + CASE WHEN <Condition 1> THEN <Expression 1>
WHEN <Condition 2> THEN <Expression 2>
WHEN <Condition 3> THEN <Expression 3>
WHEN <Condition 4> THEN <Expression 4>
END
FOR XML PATH(''), ROOT('MyString'), TYPE).value('/MyString[1]'<span clas
Ione -
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. -
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 many levels can i nest my CASE expression in a Update or any DML statement?
Hi,
Columns can have aliases; expressions that are just part of computing a column can't have aliases.
If you could assign an alias, Oracle doesn't provide any way to reference it.
If you need to reference an expression, make it a separate column, perhaps in a sub-query. -
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. -
select count(*)
from vwsr_all_merged_data s
where sr_tio_priority in ('Level 0','CEO','TER','Priority Assistance','Enquiry')
and sr_status = 'Open'
and SR_BUS_UNIT IN ('Business Support and Improvement','Finance and Administration','Cust Sat Simplification and Productivity','Project New and Customer Experience','Corp Strategy and Customer Experience','Other')
COUNT(*)
126the same should be possible dynamically with Case expression ,before that i create the string as
SELECT
CASE
WHEN :name = 'BS&I' THEN ('('||''''||'Business Support and Improvement'||''''||','||''''||'Finance and Administration'||','||''''||'Cust Sat Simplification and Productivity'
||''''||','||''''||'Project New and Customer Experience'||''''||','||''''||'Corp Strategy and Customer Experience'||''''||','||''''||'Other'||''''||')')
ELSE null
END
FROM dual
CASEWHEN:NAME='BS&I'THEN('('||''''||'BUSINESSSUPPORTANDIMPROVEMENT'||''''||','||
('Business Support and Improvement','Finance and Administration,'Cust Sat Simplification and Productivity','Project New and Customer Experience','Corp Strategy and Customer Experience','Other')
SQL> var name varchar2(10)
SQL> exec :name:='BS&I'
PL/SQL procedure successfully completed.the same string query i put here within subquery to make above string , it does not work.
select count(*)--sr_bus_unit,count(trunc(sr_open_date))
from vwsr_all_merged_data s
where sr_tio_priority in ('Level 0','CEO','TER','Priority Assistance','Enquiry')
and sr_status = 'Open'
and SR_BUS_UNIT IN
( SELECT
CASE
WHEN :name = 'BS&I' THEN ('('||''''||'Business Support and Improvement'||''''||','||''''||'Finance and Administration'||','||''''||'Cust Sat Simplification and Productivity'
||''''||','||''''||'Project New and Customer Experience'||''''||','||''''||'Corp Strategy and Customer Experience'||''''||','||''''||'Other'||''''||')')
ELSE null
END
FROM dual
COUNT(*)--SR_BUS_UNIT,COUNT(TRUNC(SR_OPEN_DATE))
0Edited by: user13653962 on 24/01/2013 17:09
Edited by: user13653962 on 24/01/2013 17:10No man , it is still no working , anyhow i really appreciate yours help , yours help drive me to find other way and you contributed 70% to achieve the result. Next query worked.
SQL> SET DEFINE OFF;
SQL>
SQL> SELECT COUNT (*)
2 FROM vwsr_all_merged_data s
3 WHERE sr_tio_priority IN
4 ('Level 0', 'CEO', 'TER', 'Priority Assistance', 'Enquiry')
5 AND sr_status = 'Open'
6 AND SR_BUS_UNIT IN
7 ('Business Support and Improvement',
8 'Finance and Administration',
9 'Cust Sat Simplification and Productivity',
10 'Project New and Customer Experience',
11 'Corp Strategy and Customer Experience',
12 'Other')
13 UNION ALL
14 SELECT COUNT (*) --sr_bus_unit,count(trunc(sr_open_date))
15 FROM vwsr_all_merged_data s
16 WHERE sr_tio_priority IN
17 ('Level 0', 'CEO', 'TER', 'Priority Assistance', 'Enquiry')
18 AND sr_status = 'Open'
19 AND SR_BUS_UNIT IN
20 (SELECT CASE
21 WHEN 'BS&I' = 'BS&I'
22 THEN
23 ( ''''
24 || 'Business Support and Improvement'
25 || ''''
26 || ','
27 || ''''
28 || 'Finance and Administration'
29 || ''''
30 || ','
31 || ''''
32 || 'Cust Sat Simplification and Productivity'
33 || ''''
34 || ','
35 || ''''
36 || 'Project New and Customer Experience'
37 || ''''
38 || ','
39 || ''''
40 || 'Corp Strategy and Customer Experience'
41 || ''''
42 || ','
43 || ''''
44 || 'Other'
45 || '''')
46 ELSE
47 NULL
48 END
49 FROM DUAL)
50
SQL>
SQL>
SQL> /
COUNT(*)
126
0Second Query
SQL> var name varchar2(10)
SQL> exec :name:='BS&I'
PL/SQL procedure successfully completed.
SQL> set define off
SQL> SELECT COUNT (*) --sr_bus_unit,count(trunc(sr_open_date))
2 FROM vwsr_all_merged_data s
3 WHERE sr_tio_priority IN
4 ('Level 0', 'CEO', 'TER', 'Priority Assistance', 'Enquiry')
5 AND sr_status = 'Open'
6 AND SR_BUS_UNIT IN
7 (SELECT CASE
8 WHEN :NAME = 'BS&I'
9 THEN
10 ('Business Support and Improvement')
11 ELSE
12 NULL
13 END
14 FROM DUAL
15 UNION
16 SELECT CASE
17 WHEN :NAME = 'BS&I'
18 THEN
19 ('Finance and Administration')
20 ELSE
21 NULL
22 END
23 FROM DUAL
24 UNION
25 SELECT CASE
26 WHEN :NAME = 'BS&I'
27 THEN
28 ('Cust Sat Simplification and Productivity')
29 ELSE
30 NULL
31 END
32 FROM DUAL
33 UNION
34 SELECT CASE
35 WHEN :NAME = 'BS&I'
36 THEN
37 ('Project New and Customer Experience')
38 ELSE
39 NULL
40 END
41 FROM DUAL
42 UNION
43 SELECT CASE
44 WHEN :NAME = 'BS&I'
45 THEN
46 ('Corp Strategy and Customer Experience')
47 ELSE
48 NULL
49 END
50 FROM DUAL
51 UNION
52 SELECT CASE
53 WHEN :NAME = 'BS&I'
54 THEN
55 ('Other')
56 ELSE
57 NULL
58 END
59 FROM DUAL
60 )
61 /
COUNT(*)--SR_BUS_UNIT,COUNT(TRUNC(SR_OPEN_DATE))
126
SQL> -
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,
I am writing the below program.
when case_not_found exception raises
can any one help me....
declare
i integer := 10;
l_result NUMBER;
begin
l_result:= CASE i
WHEN 1 THEN 2
WHEN 2 THEN 3
END CASE;
EXCEPTION
WHEN CASE_NOT_FOUND THEN
dbms_output.put_line(nvl(l_result,200));
end;Regards,
RajeshA case statement, when does not find an Appropriate match, raises a CASE_NOT_FOUND Exception.
On the contrary, the Case Expression, returns a NULL Value.
Since, you used a Case Statement, use the ELSE clause to return some value, say NULL, and the select statement will nto fail.
Modify it this way:
declare
i integer := 10;
l_result NUMBER;
begin
l_result:= CASE i
WHEN 1 THEN 2
WHEN 2 THEN 3
else NULL
END;
EXCEPTION
WHEN CASE_NOT_FOUND THEN
dbms_output.put_line(nvl(l_result,200));
end;Extract for Oracle Documentation
+"If the ELSE clause is omitted, the system substitutes a default action. For a CASE statement, the default when none of the conditions matches is to raise a CASE_NOT_FOUND exception. For a CASE expression, the default is to return NULL."+
Read For more info on Case Expression and Case Statement
Edited by: Purvesh K on Dec 13, 2012 12:26 PM -
CASE Expression Syntax( PL/SQL)
Hi,
I am facing a strange problem. I want touse CASE expression. I am facing the following error in PL/sql.
can somebody plz tell me where i am wrong? wht's exact syntax of CASE in Plsql.
1 declare
2 var1 number;
3 begin
4 var1:=2;
5 case var1
6 when 1
7 dbms_output.put_line('1');
8 when 2 dbms_output.put_line('2');
9 else dbms_output.put_line('else');
10 end case;
11* end;
SQL> /
case var1
ERROR at line 5:
ORA-06550: line 5, column 1:
PLS-00103: Encountered the symbol "CASE" when expecting one of the following:
begin declare end exception exit for goto if loop mod null
pragma raise return select update while <an identifier>
<a double-quoted delimited-identifier> <a bind variable> <<
close current delete fetch lock insert open rollback
savepoint set sql execute commit forall
<a single-quoted SQL string>
Thx in Advance.
NamrataI wrote a simple test:
select case 3
when 1 then 'true'
when 0 then 'false'
else 'maybe'
end
from dual
and this works fine. Now I tried to write a PL/SQL function as a test and got errors. Please help!
create or replace function hiSpecEval(evalOper in varchar2, evalVal in number)
return number is
Result number;
begin
case 3
when 1 then result := 1
when 0 then result := 'false'
else result := 'maybe'
end
return(Result);
end hiSpecEval;
and I got errors:
Compilation errors for FUNCTION PJ.HISPECEVAL
Error: PLS-00103: Encountered the symbol "WHEN" when expecting one of the following:
* & = - + ; < / > at in is mod not rem <an exponent (**)>
<> or != or ~= >= <= <> and or like between ||
Line: 7
Text: when 0 then result := 'false'
Error: Hint: Parameter 'evalOper' is declared but never used in 'hiSpecEval'
Line: 1
Text: create or replace function hiSpecEval(evalOper in varchar2, evalVal in number)
Error: Hint: Parameter 'evalVal' is declared but never used in 'hiSpecEval'
Line: 1
Text: create or replace function hiSpecEval(evalOper in varchar2, evalVal in number)
Error: Hint: Value assigned to 'result' never used in 'hiSpecEval'
Line: 6
Text: when 1 then result := 1 -
Cube or Group By columns with Case Expressions with a total row (SQL Server 2008)
I am trying to create a summary tabe of some data. I think that I can use Cube(my heart is not set on it though), but I cant figure a way to define new columns via a case expression and sum the new column. Lastly, I need to create a total row at the
bottom and I have no idea of how to do that except percent run the query and then run it again without the travel_city and union all the two tables
group by travaled_city, [COL1] =sum(expense) when dept = 1, [COL2]=sum(expense) when dept = 2, [COL3] = sum(expense) when group = 3, =[COL4]=sum(expense) when group = 1 and expense code = 0100,[COL5]= sum(expense) when group = 2 and expense code
= 0100, [COL6]sum(expense) when group = 3 and expense code = 0100, [COL7]=sum(expense) when (exp_paid)<30, [COL8] = sum(expense) when dept in ('4','5','6')
and have a grand total of each column
any help is greatly appreciatedWould this work?
select travaled_city,
sum(case dept when 1 then expense else 0 end) as [COL1],
sum(case dept when 2 then expense else 0 end) as [COL2], ...
Maybe you are looking for
-
When I try to purchase songs in the ITune Store a message pops up and says my session is timed out and to make sure my network settings are correct.
-
I display text in sql report. Text has 1000 characters. I would display this text in more rows(not recors).I tried set up report/edit TEXT/Tabular Form Element/element width : 20 (for example), but it is not function. It is too long row(column TEXT)
-
What is my iPad's MAC Address?
My household network only allows known (registered) MAC addresses to transceive through the wireless router. How do I obtain the MAC address for my new iPad so that I can enter it into the router's table of allowed devices? Why wasn't the MAC address
-
Vendor account exists for employees in FI. Now Travel Management is implemented. Do we need to map employees to Vendor accounts and use transaction HRP? Reimbursement will be thru FI payment? All expenses will be mapped to G/L accounts thru HRT what
-
Getting error "URI index 0 is not valid" in Oracle Service Bus
Dear Friends, I am receiving an error "URI index 0 is not valid" while executing Customization File in Oracle Service Bus. I am not able to figure out why it is happening. Please help. Thank you. Regards, Palak Mathur