Case expression in SQL
Hello every one,
I am trying case it is giving me an error of missing expression, not sure what am i missing.
It in the document.
http://download-east.oracle.com/docs/cd/A91202_01/901_doc/server.901/a90125/expressions5.htm#1033394
SQL> ed
Wrote file afiedt.buf
1 SELECT
2 CASE sal
3 WHEN < 2000 THEN
4 205
5 WHEN >='2000' THEN
6 206
7 END
8 FROM EMP
9* WHERE deptno=10
SQL> /
WHEN < 2000 THEN
ERROR at line 3:
ORA-00936: missing expression
SQL> ed
Wrote file afiedt.buf
1 SELECT
2 (CASE TRUNC(hiredate)
3 WHEN < TO_DATE ('11/17/1981', 'mm/dd/yyyy') THEN
4 205
5 WHEN >=TO_DATE ('11/17/1981', 'mm/dd/yyyy') THEN
6 206
7 END)
8 FROM EMP
9* WHERE deptno=10
SQL> /
WHEN < TO_DATE ('11/17/1981', 'mm/dd/yyyy') THEN
ERROR at line 3:
ORA-00936: missing expression
SQL> select * from v$version;
BANNER
Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
PL/SQL Release 9.2.0.8.0 - Production
CORE 9.2.0.8.0 Production
TNS for HPUX: Version 9.2.0.8.0 - Production
NLSRTL Version 9.2.0.8.0 - Productionwhen i use this it works ok, is this the verson issue,
SQL> ed
Wrote file afiedt.buf
1 SELECT
2 (CASE
3 WHEN TRUNC(hiredate)< TO_DATE ('11/17/1981', 'mm/dd/yyyy') THEN
4 sysdate
5 WHEN TRUNC(hiredate)>=TO_DATE ('11/17/1981', 'mm/dd/yyyy') THEN
6 sysdate-1
7 END) date_value
8 FROM EMP
9* WHERE deptno=10
SQL> /
DATE_VALU
22-OCT-07
21-OCT-07
21-OCT-07
It's not a version issue, but a usage issue.
You cannot use CASE WHEN on a range of value (>,<,...) but with equal, which is usefull when you have to compare a lot of value.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Production
With the Partitioning, OLAP and Data Mining options
SQL> SELECT
2 CASE sal
3 WHEN < 2000 THEN
4 205
5 WHEN >='2000' THEN
6 206
7 END
8 FROM EMP
9 WHERE deptno=10;
WHEN < 2000 THEN
ERROR at line 3:
ORA-00936: missing expression
SQL> SELECT
2 CASE sign(sal-2000)
3 WHEN -1 THEN
4 205
5 ELSE 206
6 END
7 FROM EMP
8 WHERE deptno=10;
CASESIGN(SAL-2000)WHEN-1THEN205ELSE206END
206
206
206
SQL> SELECT
2 CASE WHEN sal < 2000 THEN
3 205
4 ELSE 206
5 END
6 FROM EMP
7 WHERE deptno=10;
CASEWHENSAL<2000THEN205ELSE206END
206
206
206
SQL> Nicolas.
Similar Messages
-
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 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. -
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], ... -
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 -
Update Statement(with Case) in PL/SQL Block
Can we use Oracle case syntax (In a Update SQL)in a PL/SQL Block .
UPDATE table_name a
SET a.colum1 =
case when a.col2 IN (SELECT col1
FROM table_name1 b )
then 'Y'
else 'N'
end
It throws me an Error of code PLS-00103(This error message is from the parser. It found a token (language element) that is inappropriate in this context.)
Is there any alternative...
Thanx in Advance
nullAlas, PL/SQL has own SQL parser, and this parser dosn't know about CASE expressions (at least, it's true up to Oracle 8.1.7).
Try to use DECODE instead, something like
UPDATE table_name a
SET a.colum1 =
SELECT decode(count(*),0,'N','Y)
FROM table_name1 b
WHERE b.col1=a.colum1 -
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 unable to convert the below ssrs expression to sql query. can you guys help.
-- IIF(Parameters!parameter1.Value Is Nothing,
-- " 3>2 ",
-- "column1 NOT LIKE
-- Replace(IIF(Left(Parameters!parameter1.Value, 1) = "'",
-- Parameters!parameter1.Value,
-- "'" & Replace(Parameters!parameter1.Value, "'", "''") "'"),
Thanks.Thank you for your response Carnegie,
I actually have two stored procedures as below. (columns and joined tables are excluded)
I need to change the dates of @DateFrom and @DateTo parameter, I am passing @DateFrom_FD and @DateTo_LD as well.
CREATE ROCEDURE [dbo].[Test]
(@DateFrom
SMALLDATETIME
, @DateTo
SMALLDATETIME
, @program
VARCHAR(MAX))
AS
DECLARE
@DateFrom_FD
SMALLDATETIME
, @DateTo_LD
SMALLDATETIME
SET @DateFrom_FD = DATEADD(MONTH,DATEDIFF(MONTH,0,@DateFrom),0)
SET @DateTo_LD = DATEADD(DAY,-1,DATEADD(MONTH,DATEDIFF(MONTH,0,@DateTo)+1,0))
SELECT
DimDate.[Year]
, DimDate.[Month]
, DimDate.PK_Date
, CustomerID
FROM DimDate
WHERE DimDate.PK_Date BETWEEN @DateFrom_FD AND @DateTo_LD
Now I am using one of the SP as a main report and the other SP as a subreport.
In order to configure the main report and the subreport, I believe that I need to link them with parameters.
However, in the parameters of subreport properties, the option given are only @DateFrom and @DateTo.
No @DateFrom_FD AND @DateTo_LD
Therefore, I am thinking to use expressions to convert @DateFrom and @DateTo the same way I did in SQL.
I am not sure if this works....but this is the only thing that I could think of.
Thank you,
YJB5151 -
How to change sql expression of SQL-Calculated Attribute of view object ?
Hi
jdev 11.1.1.5
I have a view object with a SQL-Calculated Attribute (sumAnalytic) how can I change sql expression of this attribute in runtime?
for example in application module method??Hi Mr Timo
Thanks for your reply but I do not need dynamic vo because I can not change all of my vo
I only need to change expression of SQL-Calculated Attribute of view object in run time.
For this I set expression in view object something like this 'select 2 from dual' and in run time in my AM method I get the vo query and replace 'select 2 from dual' with something like 'selet sum(amnt) over (partition by 1)' and set new query.
But I think the better solution must exist
Thanks -
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.
Maybe you are looking for
-
Serious Battery Problem: Lack of Charge and Quick Drain
I have a 15" Macbook Pro purchased late July/early August 2008, model number A1260 and has its software completely updated. I use the computer every day and, aside from the occasional cycling after getting the battery charge down to 0%, charge the co
-
Need Help on How to Change The Encryption Key and or Change security settings
Hello, i just installed the wireless router and i would like to know how i can change the encryption key or change the security settings (i want it so you do not have to answer it with a password). Thank you in advance. Message Edited by DARK_MARIO o
-
Call tp EP and sending multiple rows of records
Hello friends, I am creating a screen and am sending back to EP an user ID. However I would like to send Multiple User-Ids. Below is the code of what AM I doing. str = userid. " NOTE - I would like to send Multiple IDS. lv_value_
-
i see strange red light the bottom the my Mac pro black cylinger. its went out about less than 3 sec. so what was that??
-
Unable to join domain when OD Master is set up as PDC
Hi all, I'm working on trying to get my OD server to authenticate our new windows vmware workstations. I have both LDAP and Kerberos set up, and everything works really well with my OS X clients, as do our Linux servers. However, I'm unable to get ou