sql if else语句
时间: 2023-10-01 11:08:35 浏览: 74
在SQL中,通常使用CASE语句来实现条件判断。CASE语句有两种形式:简单CASE表达式和搜索CASE表达式。
简单CASE表达式的语法如下:
```
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
...
ELSE default_result
END
```
其中,`expression`是需要判断的表达式,`value1`、`value2`等是需要与`expression`进行比较的值,`result1`、`result2`等是与`value1`、`value2`等相对应的结果,`default_result`是如果所有比较都不匹配时的默认结果。
例如,下面的语句将根据`score`的值返回不同的等级:
```
SELECT
CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 80 THEN 'B'
WHEN score >= 70 THEN 'C'
WHEN score >= 60 THEN 'D'
ELSE 'F'
END AS grade
FROM
scores;
```
搜索CASE表达式的语法如下:
```
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END
```
其中,`condition1`、`condition2`等是需要进行比较的条件,`result1`、`result2`等是与`condition1`、`condition2`等相对应的结果,`default_result`是如果所有条件都不匹配时的默认结果。
例如,下面的语句将根据`gender`的值返回不同的问候语:
```
SELECT
CASE
WHEN gender = 'male' THEN 'Hello, sir!'
WHEN gender = 'female' THEN 'Hello, madam!'
ELSE 'Hello!'
END AS greeting
FROM
users;
```
注意,在SQL中并没有像其他编程语言中的if-else语句那样的形式,但是使用CASE语句可以达到类似的效果。
阅读全文
相关推荐

















