Decode and Case
Hi,
What is the difference between decode and case?
What are the cases in which we can use Decode and case
Thanx
you can not put Search CASE statements by using DECODE
Eg:
SELECT AVG(CASE WHEN e.salary > 2000 THEN e.salary ELSE 2000 END) "Average Salary" FROM employees e;Can't we?
select avg(decode(sign(e.salary - 2000), 1, e.salary, 2000)) "Average Salary" from employees e;
Similar Messages
-
Hi
I need small clarification about difference between decode and case
Thanks who visit my threadAnd for those people who can't be ar$ed to follow links...
Decode allows for conditional output where the conditions are straightforward matches between values.
Case allows for regular conditions to be used such as greater than, less than etc.
Some of the things done by case can be achieved through decode as well but in a more convoluted manner than simply using case.
;) -
How does decode and case works?
Hi,
I want to know how decode and case works? How they process the arguements. Please explain me with some examples.
Thanks,
Sarav
Edited by: 943941 on Jul 3, 2012 1:42 AMwelcome
check this link
https://forums.oracle.com/forums/ann.jspa?annID=1535
you will find everything you need
DECODE compares expr to each search value one by one. If expr is equal to a search, then Oracle Database returns the corresponding result. If no match is found, then Oracle returns default. If default is omitted, then Oracle returns null.
This example decodes the value warehouse_id. If warehouse_id is 1, then the function returns 'Southlake'; if warehouse_id is 2, then it returns 'San Francisco'; and so forth. If warehouse_id is not 1, 2, 3, or 4, then the function returns 'Non domestic'.
SELECT product_id,
DECODE (warehouse_id, 1, 'Southlake',
2, 'San Francisco',
3, 'New Jersey',
4, 'Seattle',
'Non domestic')
"Location of inventory" FROM inventories
WHERE product_id < 1775;Edited by: user 007 on Jul 3, 2012 2:40 PM -
More effecient way of using Decode and CASE
Is it possible to use both case and decode together? I feel I have too many decode and I am not sure how to write this in a more efficient way.
I would really appreciate any help.
Thank you so much in advance!!!
SELECT Person_ID,Work_ID,
CASE WHEN NBR = 1 THEN
MIN(DECODE(NBR, 1, field1)) aug_one_field1;
MIN(DECODE(NBR, 1, field2)) aug_one_field2;
MIN(DECODE(NBR, 1, field3)) aug_one_field3;
MIN(DECODE(NBR, 1, field4)) aug_one_field4;
MIN(DECODE(NBR, 1, field5)) aug_one_field5;
MIN(DECODE(NBR, 1, field6)) aug_one_field6;
CASE WHEN NBR = 2 THEN
MIN(DECODE(NBR, 2, field1)) aug_two_field1;
MIN(DECODE(NBR, 2, field2)) aug_two_field2;
MIN(DECODE(NBR, 2, field3)) aug_two_field3;
MIN(DECODE(NBR, 2, field4)) aug_two_field4;
MIN(DECODE(NBR, 2, field5)) aug_two_field5;
MIN(DECODE(NBR, 2, field6)) aug_two_field6;
CASE WHEN NBR = 3 THEN
MIN(DECODE(NBR, 3, field1)) aug_three_field1;
MIN(DECODE(NBR, 3, field2)) aug_three_field2;
MIN(DECODE(NBR, 3, field3)) aug_three_field3;
MIN(DECODE(NBR, 3, field4)) aug_three_field4;
MIN(DECODE(NBR, 3, field5)) aug_three_field5;
MIN(DECODE(NBR, 3, field6)) aug_three_field6;
CASE WHEN NBR = 4 THEN
MIN(DECODE(NBR, 4, field1)) aug_four_field1;
MIN(DECODE(NBR, 4, field2)) aug_four_field2;
MIN(DECODE(NBR, 4, field3)) aug_four_field3;
MIN(DECODE(NBR, 4, field4)) aug_four_field4;
MIN(DECODE(NBR, 4, field5)) aug_four_field5;
MIN(DECODE(NBR, 4, field6)) aug_four_field6;
END
FROM (SELECT Person_ID,Work_ID, NBR
fiel1, field2, field3,field4,field5, field6,
FROM field_rep
GROUP BY Person_ID,Work_IDThanks alot John and Frank.
John to answer your question, I just felt the 24 or more decode will slow down the systems performance, hence I was trying to find a better way to do it.
Frank
This is a sample data but I want it pivoted hence the reason for using the decode. I have oracle 10g. These are sample data
Person_id work_id NBR field1 field2 field3 field4 field5 field6
1 ao334 1 1/2/2009 1/9/2010 block_A HH 55667 1
1 ao334 2 5/2/2011 9/9/2013 block_Z HL 11111 3
1 ao334 2 1/2/2009 1/9/2010 block_A HH 22222 1
1 ao334 4 1/2/2009 1/9/2010 block_A HH zzzzz 7
1 z5521 1 10/5/2006 12/31/2012 block_C SS 33322 1
1 z5521 2 1/2/2009 1/9/2010 block_C SS 21550 1
1 z5521 3 1/2/2009 1/9/2010 block_R SS 10000 1
1 z5521 4 1/2/2009 1/9/2010 block_D SS 99100 5
1 z5521 5 1/2/2009 1/9/2010 block_P SS 88860 1
1 z5521 6 1/2/2009 1/9/2010 block_G SS 99660 8
1 ob114 1 1/2/2009 1/9/2010 block_A HH 52333 1
1 ob114 2 1/2/2009 1/9/2010 block_A HH 88888 1Output will look like this
Person_id work_id aug_one_field1 aug_one_field2 aug_one_field3 aug_one_field4 aug_one_field5 aug_one_field6 aug_two_field1 aug_two_field2 aug_two_field3 aug_two_field4 aug_two_field5 aug_two_field6
1 ao334 1/2/2009 1/9/2010 block_A HH 55667 1 5/2/2011 9/9/2013 block_Z HL 11111 3 -
What is better and fast to use between decode and case
Hi friends,
i wanted to know what is better to use decode or case in sql,which gives faster result.
thks
sonal....Here's a very simple timing comparison. This table (actually it's a partition) has a little over 1 million rows.
As you can see, the timing difference is trivial. (I ran an earlier query to fetch the blocks from disk).
SQL> select sum(decode(balloon_flag
2 ,'Y',1
3 ,0
4 )
5 ) bal_count
6 from prod.loan_master
7 where report_date = to_date('31-DEC-2005');
BAL_COUNT
9036
Elapsed: 00:00:07.65
SQL> select sum(case balloon_flag
2 when 'Y' then 1
3 else 0
4 end
5 ) bal_count
6 from prod.loan_master
7 where report_date = to_date('31-DEC-2005');
BAL_COUNT
9036
Elapsed: 00:00:07.68
SQL> select sum(case
2 when balloon_flag = 'Y' then 1
3 else 0
4 end
5 ) bal_count
6 from prod.loan_master
7 where report_date = to_date('31-DEC-2005');
BAL_COUNT
9036
Elapsed: 00:00:07.46 -
Decode and case statement in the update..
Its is more to it, but I want to check with you guys, the experts on this, this look busy to me, it should be a more simplify way of doing it, do you think will work
The government decide to change the ethnic codes, and we have to come with certain rules to in our report, anyway, do you think this will work? again It is more to it I declare my variables, this is just one part of the precedure.
BEGIN
UTL_FILE.fclose_all;
v_file_handle := UTL_FILE.fopen (v_out_path, v_out_file, 'a');
UTL_FILE.put_line (v_file_handle,
CHR (10) || TO_CHAR (SYSDATE, 'DD-MON-YYYY HH:MI:SS')
UTL_FILE.put_line (v_file_handle, 'Entering spbpers_update');
SELECT upd_spbpers_upd_cur IS
spriden_pidm,
szscapp_birth_state,
szscapp_birth_city,
DECODE(szscapp_hisp_or_latino_ind,Y,'2',N,'1'),
DECODE(szscapp_hisp_or_latino_options,XCM,'2',CUB,'2',MEX,'2',PRI,'2',XSM,'2',ESP,'2',XOH,'2'),
DECODE(szscapp_amer_indn_alaska_opt,XAN,'1','1',XCW,'1',XCH,'1',XCK,'1',XNV,'1',XSX,'1'),
DECODE(szscapp_amer_indn_alaska_other,XON,'1') (,IND,'1',JPN,'1',KOR,'1',PAK,'1',PHL,'1',VNM,'1',XEA,'1',XIS,'1',XSA,'1'),
DECODE(szscapp_asian_options,IND,'1',JPN,'1',KOR,'1',PAK,'1',PHL,'1',VNM,'1',XEA,'1',XIS,'1',XSA,'1'), ,
DECODE(szscapp_other_east_asia,(IND,'1',JPN,'1',KOR,'1',PAK,'1',PHL,'1',VNM,'1',XEA,'1',XIS,'1',XSA,'1'),
DECODE(szscapp_other_indian_subcont,XIS,'1'),
DECODE(szscapp_other_southeast_asia,XSA,'1'),
DECODE(szscapp_blk_or_afr_amer_opt,XAA,'1',XAF,'1',XCB,'1',XOA,'1'),
DECODE(szscapp_blk_or_afr_amer_other,XOA,'1'),
DECODE(szscapp_natve_hawaian_options,GUM,'1',XHI,'1',ASM,'1',XOP,'1'),
DECODE(szscapp_hawaiian_other,XOP,'1'),
DECODE(szscapp_white_options,XEU,'1',XME,'1',XOW,'1'),
DECODE(szscapp_white_other(XOW,'1')
FROM
saturn_midd.szscapp
WHERE
spriden_id = szscapp_id
AND spriden_ntyp_code = 'CAPL'
IF upd_spbpers_upd_cur%ISOPEN
THEN
CLOSE upd_spbpers_upd_cur;
END IF;
OPEN upd_spbpers_upd_cur;
LOOP
FETCH upd_spbpers_upd_cur
INTO v_pidm,v_birth_state,v_birth_city,v_latino_ind,v_latino_options,
v_indn_alaska_opt,v_indn_alaska_other,v_asian_options,
v_other_east_asia,v_other_indian_subcont,v_other_southeast_asia,
v_blk_or_afr_amer_opt,v_blk_or_afr_amer_other,v_natve_hawaian_options,
v_hawaiian_other,v_white_options,v_white_other;
EXIT WHEN upd_spbpers_upd_cur%NOTFOUND;
IF upd_spbpers_upd_cur%FOUND
UPDATE saturn.spbpers
set SPBPERS_ETHN_CODE = CASE
WHEN v_latino_ind IS NOT NULL THEN (spbpers_ethn_code = v_latino_ind,spbpers_activity_date = sysdate)
WHEN v_latino_options IS NOT NULL THEN (spbpers_ethn_code = v_latino_options,spbpers_activity_date = sysdate)
WHEN v_indn_alaska_opt IS NOT NULL THEN (spbpers_ethn_code = v_indn_alaska_opt,spbpers_activity_date = sysdate)
WHEN v_indn_alaska_other IS NOT NULL THEN (spbpers_ethn_code = v_indn_alaska_other,spbpers_activity_date = sysdate)
WHEN v_asian_options IS NOT NULL THEN (spbpers_ethn_code = v_asian_options,spbpers_activity_date = sysdate)
WHEN v_other_east_asia IS NOT NULL THEN (spbpers_ethn_code = v_other_east_asia,spbpers_activity_date = sysdate)
WHEN v_other_indian_subcont IS NOT NULL THEN (spbpers_ethn_code = v_other_indian_subcont,spbpers_activity_date = sysdate)
WHEN v_other_southeast_asia IS NOT NULL THEN (spbpers_ethn_code = v_other_southeast_asia,spbpers_activity_date = sysdate)
WHEN v_blk_or_afr_amer_opt IS NOT NULL THEN (spbpers_ethn_code = v_blk_or_afr_amer_opt,spbpers_activity_date = sysdate)
WHEN v_blk_or_afr_amer_other IS NOT NULL THEN (spbpers_ethn_code = v_blk_or_afr_amer_other,spbpers_activity_date = sysdate)
WHEN v_natve_hawaian_options IS NOT NULL THEN (spbpers_ethn_code = v_natve_hawaian_options,spbpers_activity_date = sysdate)
WHEN v_hawaiian_other IS NOT NULL THEN (spbpers_ethn_code = v_hawaiian_other,spbpers_activity_date = sysdate)
WHEN v_white_options IS NOT NULL THEN (spbpers_ethn_code = v_white_options,spbpers_activity_date = sysdate)
WHEN v_white_other IS NOT NULL THEN (spbpers_ethn_code = v_white_other,spbpers_activity_date = sysdate)
WHEN v_birth_state IS NOT NULL THEN (spbpers_stat_code_birth = v_birth_state,spbpers_activity_date = sysdate)
WHEN v_birth_city IS NOT NULL THEN (spbpers_city_birth = v_birth_city,spbpers_activity_date = sysdate)
WHERE spbpers_pidm = v_pidm;
END
END IF;
END LOOP;Did the procedure compile ?
Doesn't look like a right Decode syntax.
DECODE (col1,'VAL1','This','VAL2','That','ElseThis')
means
--Psuedocode
IF col1 = 'VAL1' THEN 'This'
IF col1 = 'VAL2' THEN 'That'
ELSE 'ElseThis'You can use CASE statement Instead of DECODE
CASE
when szscapp_amer_indn_alaska_other
in ('XON','IND','JPN','KOR','PAK' ..... ) THEN '1'
when szscapp_hisp_or_latino_options
in ('XCM','CUB','MEX','PRI','XSM','ESP','XOH' ...) THEN '2'
END SS -
I am having issue in group by using decode and case in pl/sql
my query is some thing like this but having more column in select. when i am firing this query it is giving result but that is not proper
my problem is , like if there are 3 more values for uh.sflowtype (0,1,2) then group by is not working for them and those are coming in different row , i need them to be combined
query is :
select substr(uh.sstartdatetime,1,8) DateTime,
( case
when uh.sflowtype=7 then 'sms'
when uh.sflowtype=9 then 'mms'
when uh.sflowtype=10 then 'gprs'
else 'voice'
end )
as flowtype from e_vpn_usagehistory uh where 1=1 and uh.nspid='1' AND ((substr(uh.sstartdatetime,1,8) >= 20130507 )
AND (substr(uh.sstartdatetime,1,8) <= 20130606)) GROUP BY substr(uh.sstartdatetime,1,8),uh.sflowtype
order by substr(uh.sstartdatetime,1,8) DESC
result :
DATETIME FLOWTYPE
20130507 voice
20130507 voice
20130507 voice
20130507 sms
20130507 mms
but i need
20130507 voice
20130507 sms
20130507 mms
so what should i do?
please suggest me996962 wrote:
my query is some thing like this but having more column in select. when i am firing this query it is giving result but that is not proper
my problem is , like if there are 3 more values for uh.sflowtype (0,1,2) then group by is not working for them and those are coming in different row , i need them to be combined
query is :
select substr(uh.sstartdatetime,1,8) DateTime,
( case
when uh.sflowtype=7 then 'sms'
when uh.sflowtype=9 then 'mms'
when uh.sflowtype=10 then 'gprs'
else 'voice'
end )
as flowtype from e_vpn_usagehistory uh where 1=1 and uh.nspid='1' AND ((substr(uh.sstartdatetime,1,8) >= 20130507 )
AND (substr(uh.sstartdatetime,1,8) <= 20130606)) GROUP BY substr(uh.sstartdatetime,1,8),uh.sflowtype
order by substr(uh.sstartdatetime,1,8) DESC
result :
DATETIME FLOWTYPE
20130507 voice
20130507 voice
20130507 voice
20130507 sms
20130507 mms
but i need
20130507 voice
20130507 sms
20130507 mms
so what should i do?
please suggest meWell, you are grouping by substr(uh.sstartdatetime,1,8),uh.sflowtype
so different values of sflowtype that aren't 7,9 or 10 will be grouped separately.
You therefore need to group by your case statement instead of just the sflowtype.
The most worrying thing though is that you have sstartdatetime that appears to be a varchar2 and not a date.
If it is a date, you are applying a substr (which applies to strings) to a date. you then compare the result
of the substr to a number.
This is a recipe for future problems: sort it out using the correct conversion functions with format masks.
Edited by: Paul Horth on May 14, 2013 1:25 PM -
DECODE OR CASE - Which is better and why
Oracle version: 11.2
Problem: We have a huge table with 10M records, which needs to be processed daily.
While loading data in table we have to handle condition if flag is =1 then '111' else '000'
To implement this which one is efficient solution? .. using CASE or DECODE and why?
Example:
SQL> select flag,case when flag='Y' then '111' else '000' end from (select 'Y' as flag from dual union all select 'N' from dual);
F CAS
Y 111
N 000
SQL> select flag,decode(flag,'Y','111','000') from (select 'Y' as flag from dual union all select 'N' from dual);
F DEC
Y 111
N 000Hi,
For this job, they're equally efficient.
For any job, where DECODE doesn't require a lot more code than CASE, they will be equally efficient.
I recommend (almost) always using CASE. It's easier to understand and debug, and, if written correctly, will never be slower than DECODE.
The only situation where I use DECODE is for very simple tasks (like the one you posted) where this is used inside a very complicated expression, and the slightly less coding needed for DECODE makes the larger statement easier to read. -
Efficiency of decoding and displaying image files?
BRIEF SUMMARY
My question is this: can Flash Player download JPG and GIF
files from a server and rapidly open/decode them, ready for
display, efficiently and
entirely 'in memory'?
Would Flex be a good choice of language for developing a RIA
that needs to continually download lots of JPG and GIF images
on-the-fly from the server and render them on the screen? I *don't*
want my application to thrash the hard disc.
BACKGROUND
I am designing a 'rich' web app, and I'm investigating
whether Flex is the right tool for the job.
Although Flash's animation features are an obvious selling
point for implementing my user interface, I also need to do some
server-side rendering. What I want to do is perhaps a little
unorthodox: I will be generating lots of GIF and JPG files on the
fly and these will be streamed to the client (along with other
application data, e.g. in XML format) to update different parts of
the on-screen document. In need this to happen very quickly (in
some cases, creating the effect of animation).
It happens that JPGs and 16-colour GIFs will be, by far, the
most efficient formats for streaming the images, because of the
nature of the application. I could of course send the images in
some proprietary format, geared for my application, but presumably
decoding the images would be slow as I would have to implement this
myself in ActionScript, and so I would be limited by the speed of
Flex 'bytecode'. (I realise Flash is a lot more optimised than it
once was, but I am hoping to see a gain from using image formats
that Flash natively understands!)
Naturally the internet bandwidth should (in principle) be the
bottleneck. However, assuming I can get my image files to the
client on time, want I want to know is:
how efficient is Flash at loading such files?
Bearing in mind that I'm not just displaying the occasional
image -- I will be doing this continuously. Most of the images
won't be huge, but there will be several separate images per
second.
The image files will be a mixture of normal colour JPGs and
4-bit colour GIFs (LZW-compressed). I know that Flash natively
supports these formats, but depending on how Adobe have implemented
their LZW/Huffman decoding and so on, and how much overhead there
is in opening/processing downloaded image files before they are
ready to 'blit' to the screen, I imagine this could be pretty fast
or pretty slow!
If my client only has a modest PC, I don't want the JPG/GIF
decoding alone to be thrashing his CPU (or indeed the disc) before
I've even got started on 'Flashy' vector stuff.
I'm new to Flash, so are there any 'gotchas' I need to know
about?
E.g. Would it be fair to assume Flash Player will do the
decoding of the downloaded image entirely 'in memory' without
trying to do anything clever like caching the file to disc, or
calling any libraries which might slow down the whole process? It
would be no good at all if the images were first written to the
client's hard disc before being ready to display, for example.
Further, if I'm doing something a little out-of-the-ordinary,
and there is no 'guarantee' that images will be loaded quickly,
what I'm doing might be a bad idea if a later version of Flash
Player may (for example) suddenly start doing some disc access in
the process of opening a newly downloaded image. So, while I could
just 'try it and see', what I really need is some assurance that
what I'm doing is sensible and is likely to carry on working in
future.
Finally, I imagine JPG/GIF decoding could be something that
would vary from platform to platform (e.g. for the sake of
argument, Flash Player for Windows could use a highly-optimised
library, but other versions could be very inefficient).
This could be the 'make or break' of my application, so all
advice is welcome! :) Thanks in advance.You need a servlet/jsf component to render the image in the response.
Look at this: http://www.irian.at/myfaces-sandbox/graphicImageDynamic.jsf -
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. -
Which is the best decode or case
Hi,
When you check performance wise which is the best one decode or case?
Thanks,> You mean CPU processor speed or oracle buffer(SGA).
Neither. CPU architecture. RISC vs CISC vs ..
On a PA-RISC1 CPU a DECODE is just a tad faster than a CASE. On an AMD64 CPU, the reverse is true.
> When I increase memory, The case and decode performance will increase?
No. A CASE and a DECODE does not need memory to work faster. It is a set of machine code instructions that needs to compare values to determine a result. It depends on just how fast the CPU can execute this set of machine code instructions.
A faster CPU will make a very significant difference. An AMD64 Opteron CPU is a couple of times faster than a PA-RISC1 CPU.
I had this exact same conversation back in 2006 on this forum - and posted [url
http://forums.oracle.com/forums/thread.jspa?messageID=1346165�]this benchmark to show that the decision of using CASE or DECODE is not a decision that should be based on raw performance. -
I'm a beginner with Oracle SQL and I have a select statement with the following code:
max(decode(EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_CD, '1000', EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_RESULT_TEST_SCORE, '2000', EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_RESULT_TEST_SCORE, '4000', EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_RESULT_TEST_SCORE))
I've been asked to create several more columns in a similar manner. My concern is that since this relies on 'decode' which is less efficient than 'case', that adding more columns using this approach will bog down an already not efficient query. Bottom line my problem is that I don't really understand this 'decode' since all the explanations of 'decode' I've found stop at four parameters.
Could someone please show me how the expression above looks in If-then-else terms as well as comment on how to convert this 'decode' to 'case'? Thanks in advance!1) The if-then-else stmt
-- Longest way
if EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_CD = '1000' then
return value of EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_RESULT_TEST_SCORE;
elsif EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_CD = '2000' then
return value of EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_RESULT_TEST_SCORE;
elsif EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_CD = '4000' then
return value of EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_RESULT_TEST_SCORE;
else return null;
end if;
-- shorter way
if EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_CD = '1000' or
EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_CD = '2000' or
EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_CD = '4000' then
return value of EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_RESULT_TEST_SCORE;
else return null;
end if;
-- shortest if-then-else code
if EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_CD in ('1000', '2000', '4000') then
return value of EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_RESULT_TEST_SCORE;
else return null;
end if;
2) The MAX() function
The MAX function will return the greatest value of EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_RESULT_TEST_SCORE in step 1 above.
2) Using CASE
select
max(case when (EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_CD in('1000','2000','4000'))
then EDW.V_RECRUIT_TEST_RESULT_HIST.TEST_RESULT_TEST_SCORE end)
into ...your_item_or_local_variable
from EDW.V_RECRUIT_TEST_RESULT_HIST;
Try the code above, good luck
v/r
Vien Tran -
Hello everyone
I have a network infrastructure consisting of 3 sites, site A, site B, and site C. i have 2 domain controllers on every site, and the AD roles are on the primary domain controller on site A. On site A I have an Exchange 2013sp1 CU6.
I want to create a second Exchange on Site B, with the roles of mailbox (the exchange on Site A will be first DAG member and the Exchange on Site B will be the second member of the DAG) and CAS.
First question: Is my thought correct about installaing on the same server mailbox and CAS server?
Second question: how many DAG witnesses I need for the DAG? One per site, or one in general (for example located on site A)
Third question: When I am trying to perform “Setup.exe /PrepareSchema /IAcceptExchangeServerLicenseTerms” I receive the error
“ Setup encountered a problem while validating the state of Active Directory:
The Active Directory schema version (15303) is higher than Setup's version (15292). Therefore, PrepareSchema can't be executed. See the Exchange setup log for more information on this error. For more information, visit:
http://technet.microsoft.com/library(EXCHG.150)/ms.exch.setupreadiness.AdInitErrorRule.aspx “
I tried to run the PrepareSchema from the ISO of Exchange 2013 SP1 and form the extracted content of Exchange 2013SP1 CU6 archive, but still receive the same error. Any ideas?
Thanks in advance.Thank you for your answer,
I have tried to run "Setup.exe /PrepareSchema /IAcceptExchangeServerLicenseTerms” from
Exchange 2013 CU6 media, but I still receive the error:
The Active Directory schema version (15303) is higher than Setup's version (15292). Therefore, PrepareSchema
can't be executed. See the Exchange setup log for more information on this error. For more information, visit:http://technet.microsoft.com/library(EXCHG.150)/ms.exch.setupreadiness.AdInitErrorRule.aspx “
any ideas? -
How do I use switch and case statements to fill more than one other field?
Hi all,
I'm new to the community.
I'm trying to make an existing form more user friendly for my coworkers. I want to use a switch and case approach in a drop-down list field so that the selection fills two seperate other fields with different info related to the selection.
I can already do this with one field, but if I add a second target field under an existing case the text doesn't appear there when I make the selection from the dropdown.
Basically, I'm asking if I can do this:
switch
(sNewSel){
case "1": // Selection 1 Row2.Field1
= "text for field 1";
Row1.Field2 = "text for field 2";
break;
etc.
It works if the "row1.field2" option isn't there, but not when it is present.
Any takers?I'm not sure if I will be able to send you the form. There may be too much to redact.
Would this last bit of code in the cell affect anything?
if
(bEnableTextField)
{Row2.Field1.access
= "open"; // enable field
Row2.Field1.caption.font.fill.color.value= "0,0,0"; // set caption to black
That is, do I also need to repeat the same thing for the second target cell (Row1.Field2)?
What would be possible hang ups that would prevent it from working correctly?
Dave
By the way, I'm not sure if my other attachment posted. I am trying again. -
How to decoding and encoding PNG and GIF images?
I could decode and encode JPEG images using following create functions which are in com.sun.image.codec.jpeg package.
JPEGImageDecoder decoder = JPEGCodec .createJPEGDecoder(inputStream);
JPEGImageEncoder encoder = JPEGCodec .createJPEGEncoder(outputStream);
But I dont know required package and functions to decode and encode PNG and GIF images. Please help me.Is the API that hard to follow?
ImageIO.read( file/stream/url)
ImageIO.write( image, format (e.g. PNG, GIF(1), JPEG), file/stream what have you)
1) Not sure if Java supports GIF saving, it might if you install JAI, or Java 6.
Maybe you are looking for
-
Problem crystal report xi with j2ee
dear all after greeting i have exception that appear when i open report created by crystal report and i didn't know why this exception although the report is successfully opened i am using jrc and the exception is following:: Assertion Failed: Unknow
-
IPhone 6 Trade-in Promotion - Based On A True Story...
On 9/30/14, my wife & I decided to take advantage of moving from AT&T to Verizon by joining our son-in-law’s More Everything plan. Our AT&T 2-year contract was more than satisfied. We’re both iPhone users & were looking forward to upgrading our iPhon
-
What exactly is the appId in getApplicationPolicy() ?
I need some explanation what exactly appid is in the following method: http://docs.oracle.com/cd/E12839_01/apirefs.1111/e14650/oracle/security/jps/service/policystore/PolicyStore.html#getApplicationPolicy_java_lang_String_ ApplicationPolicy getApplic
-
I am unable to sync my videos in Iphoto to my Ipad. They are taken with a Canon D10 camera and are listed as MVI.Mov. It looks like this is a compatable format but when I sync I get an error message saying they can't be played on my Ipad. Can anyone
-
There was no option to cancel or renew the purchase and "report a problem" was so complicated. By the time I report the problem the billing would have gone through anyway.