在SQL Server中打开switch case的答案

时间:2017-05-13 12:05:30

标签: sql-server switch-statement case

我想将开关盒的答案打印到控制台,我该怎么办呢?

实施例

select 
    ID, 
    order by
        Case When Marks >= 76 Then print 'Student' @ID has grade 'A'  
             When Marks >= 65 Then  print 'Student' @ID has grade 'B'
             When Marks < 35 Then  print 'Student' @ID has grade 'C'
        End as grade
From 
    Student

输出:

Student 1 has grade C
Student 2 has grade B
Student 3 has grade A

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

如果您只是想计算学生成绩并显示它们,那么您可以在SELECT语句中计算他们的成绩,而不是打印,如下所示:

SELECT 
    CASE WHEN Marks >= 76 THEN 'Student ' + CAST( ID AS VARCHAR ) + ' has grade A'  
         WHEN Marks >= 65 THEN 'Student ' + CAST( ID AS VARCHAR ) + ' has grade B'
         WHEN Marks < 35  THEN 'Student ' + CAST( ID AS VARCHAR ) + ' has grade C'
    END AS grade
FROM 
    Student