//SQL中的IF-ELSE语句
IF (条件)
BEGIN
语句1
语句2
… …
END
ELSE
BEGIN
语句1
语句2
… …
END
例子:
IF (@score > 85)
PRINT ‘考试等级:‘ + ‘优秀‘
ELSE IF (@score > 70)
PRINT ‘考试等级:‘ + ‘良好‘
ELSE IF (@score > 60)
PRINT ‘考试等级:‘ + ‘中等‘
ELSE
PRINT ‘考试等级:‘ + ‘差‘
//SQL中的WHILE语句
WHILE (条件)
BEGIN
语句1
语句2
……
BREAK
END
例子:
DECLARE @n int --不及格人数
WHILE (1 = 1) --条件永远成立
BEGIN
SELECT @n=COUNT(*) FROM Result
WHERE [email protected] AND [email protected]
AND StudentResult < 60 --统计不及格人数
IF (@n > 0) --每人加2分
UPDATE Result SET StudentResult=StudentResult+2 FROM Result
WHERE [email protected] AND [email protected] AND
StudentResult < 95
ELSE
BREAK --退出循环
END
//CASE-END多分支语句
CASE
WHEN 条件1 THEN 结果1
WHEN 条件2 THEN 结果2
……
ELSE 其他结果
END
注意:ELSE表示CASE中所有WHEN条件均不为 TRUE 时返回的结果
如果省略ELSE且WHEN条件都为FALSE时,CASE语句返回NULL
例子:
SELECT 学号=StudentNo, 成绩=
CASE
WHEN StudentResult < 60 THEN ‘E‘
WHEN StudentResult BETWEEN 60 AND 69 THEN ‘D‘
WHEN StudentResult BETWEEN 70 AND 79 THEN ‘C‘
WHEN StudentResult BETWEEN 80 AND 89 THEN ‘B‘
ELSE ‘A‘
END
FROM Result
INNER JOIN Subject ON Result.SubjectNo=Subject.SubjectNo