在SQLServer中,可以使用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;
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等語句中。