阅读量:0
在SQLServer中,可以使用CASE语句来实现根据条件选择不同的操作。CASE语句有两种形式:简单CASE表达式和搜索CASE表达式。
- 简单CASE表达式:
SELECT CASE column_name WHEN value1 THEN result1 WHEN value2 THEN result2 ... ELSE result END FROM table_name;
示例:
SELECT CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' WHEN score >= 70 THEN 'C' ELSE 'D' END AS grade FROM student;
- 搜索CASE表达式:
SELECT CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... ELSE result END FROM table_name;
示例:
SELECT CASE WHEN gender = 'M' AND age >= 18 THEN 'Man' WHEN gender = 'F' AND age >= 18 THEN 'Woman' ELSE 'Child' END AS category FROM person;
注意:在SQLServer中,CASE语句也可以嵌套使用。CASE语句可以用于SELECT、WHERE、ORDER BY等语句中。