How to use ORACLE case when and SELECT case

Source: Internet
Author: User
Tags case statement

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;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.