Saturday, November 15, 2008

Using CASE Statements in PL/SQL programs

While CASE constructs don't offer any fundamentally new semantics, they do allow a more compact notation and some elimination of repetition with respect to what otherwise would be expressed with an IF construct.

case
when n = 1 then Action1;
when n = 2 then Action2;
when n = 3 then Action3;
when ( n > 3 and n < 8 ) then Action4through7;
else ActionOther;
end case;

…and…

text := case
when n = 1 then one

when n = 2 then two
when n = 3 then three
when ( n > 3 and n < 8 ) then four_through_seven
else other
end;

For Example,
set serveroutput on;
drop function Get_Grade_Description;

create or replace function Get_Grade_Description(grade IN VARCHAR2) RETURN VARCHAR2 is
description VARCHAR2(15);
begin
-- use a CASE Expression to store the description for
-- the grade in a variable
description := CASE grade
WHEN 'A' THEN 'Excellent'
WHEN 'B' THEN 'Very Good'
WHEN 'C' THEN 'Good'
WHEN 'D' THEN 'Fair'
WHEN 'F' THEN 'Fail'
ELSE 'No such grade'
END;
-- return the description
return description;
end Get_Grade_Description;
/
Show Errors

select Get_Grade_Description('A') from dual
/

No comments:

search engine

Custom Search