Case statement
Case Selector
When value1 and then action1;
When value2 and then Action2;
When Value3 and then Action3;
.....
ELSE Actionn;
END case;
Case expression
DECLARE
Temp VARCHAR2 (10);
V_num number;
BEGIN
V_num: = &i;
Temp: = Case V_num
When 0 Then ' Zero '
When 1 Then ' one '
When 2 Then ' both '
ELSE
Null
END;
Dbms_output.put_line (' V_num = ' | | temp);
END;
/
Case Search Statement
Case
When (Boolean_condition1) then action1;
When (Boolean_condition2) then Action2;
When (Boolean_condition3) then Action3;
......
ELSE Actionn;
END case;
Case-Search Expression
DECLARE
A number: = 20;
B Number: =-40;
TMP VARCHAR2 (50);
BEGIN
TMP: = case
When (a>b) then ' A is greater than B '
When (a<b) then ' A was less than B '
ELSE
' A is equal to B '
END;
Dbms_output.put_line (TMP);
END;
/
How to use SELECT case
Select and case use the greatest advantage of two points, one is to display the results of the query can be flexible organization format, the second is to effectively avoid multiple visits to the same table or a few tables. Here is a simple example to illustrate. For example, table students (ID, name, birthday, sex, grade), the number of boys and girls required by each grade statistics, the results of the table for the grade, the number of boys, the number of girls. Assuming a Select Case is not used, in order to display the number of men and women together, the statistics are very troublesome, first determine the grade information, and then the number of boys and girls according to grade, and very easy error. Use the Select Case when you like the following:
SELECT grade, COUNT (case if sex = 1 then 1/*sex 1 for boys, 2 girls */
ELSE NULL
END) Number of boys,
COUNT (case if sex = 2 then 1
ELSE NULL
END) Number of girls
From students GROUP by grade;