Home > Database > Oracle > body text

How to use case in oracle

下次还敢
Release: 2024-05-02 23:42:36
Original
871 people have browsed it

The CASE statement in Oracle is a tool for condition evaluation. Its usage includes: specifying the condition to be evaluated (WHEN). The action (THEN) to perform if the condition is true. If all conditions are false, perform the default action (ELSE, optional).

How to use case in oracle

Usage of CASE statement in Oracle

The CASE statement is a method used for conditional evaluation in Oracle Powerful tool. It allows you to perform different actions based on given conditions.

Grammar:

<code>CASE
  WHEN condition1 THEN result1
  WHEN condition2 THEN result2
  ...
  ELSE default_result
END</code>
Copy after login

Usage:

The usage of CASE statement is as follows:

  • Conditions (WHEN): Specify the conditions to be evaluated.
  • Result (THEN): The action to perform if the condition is true.
  • Default result (ELSE): The action to perform if all conditions are false. It is optional.

Example:

The following example uses the CASE statement to determine a grade based on a student's grade:

<code class="sql">SELECT
  name,
  CASE
    WHEN score >= 90 THEN 'A'
    WHEN score >= 80 THEN 'B'
    WHEN score >= 70 THEN 'C'
    ELSE 'F'
  END AS grade
FROM students;</code>
Copy after login

CASE expression:

CASE statements can also be used as expressions, returning results evaluated based on conditions:

<code>-- 检查一个数字是否为偶数或奇数
CASE
  WHEN num % 2 = 0 THEN 'Even'
  ELSE 'Odd'
END</code>
Copy after login

Nested CASE:

CASE statements can Nesting to handle more complex conditions:

<code class="sql">SELECT
  CASE
    WHEN status = 'Active' THEN
      CASE
        WHEN balance >= 10000 THEN 'High'
        ELSE 'Low'
      END
    ELSE 'Inactive'
  END AS account_status
FROM accounts;</code>
Copy after login

Advantages:

Using the CASE statement has the following advantages:

  • Simplified condition evaluation
  • Improve code readability
  • Reduce code duplication

The above is the detailed content of How to use case in oracle. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!