Home  >  Article  >  Database  >  How to judge if statement in sql multiple times

How to judge if statement in sql multiple times

下次还敢
下次还敢Original
2024-05-01 21:51:491086browse

In SQL, multiple conditions with THEN and ELSE keywords can be used to perform multiple judgments, as follows: IF condition1 THEN -- statement block 1ELSIF condition2 THEN -- statement block 2...ELSE -- Statement block nEND IF;

How to judge if statement in sql multiple times

IF statement is used in SQL to make multiple judgments

IF statement is used in SQL Control flow statements that perform different operations based on conditions. In some cases, multiple tests are required in a single IF statement to determine the action to perform.

Syntax

Use THEN and ELSE keywords to link multiple conditions to an IF statement:

<code class="sql">IF condition1 THEN
    -- 语句块 1
ELSIF condition2 THEN
    -- 语句块 2
...
ELSE
    -- 语句块 n
END IF;</code>

Example

Suppose we have a table students, which contains students' grades. We need to query the students' grades and assign grades based on different ranges of grades:

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

In this example, the CASE statement is used to make multiple judgments based on the students' grades. Each WHEN clause specifies a condition and a corresponding level. The ELSE clause provides a default level that is used when all other conditions are not met.

Note:

  • The ELSEIF keyword is optional; it can be omitted if there is no ELSEIF condition.
  • Each WHEN clause must end with the THEN keyword, and the ELSE clause must end with the END IF keyword.
  • The CASE statement can also be used to make multiple judgments, and is preferable in some cases.

The above is the detailed content of How to judge if statement in sql multiple times. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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