T-SQL 邏輯控制語句 ifelse while casewhen
阿新 • • 發佈:2018-11-30
ifelse
1 use StudentManageDB 2 go 3 --查詢成績 4 declare @cAvg int 5 select @cAvg=avg(CSharp) from ScoreList 6 inner join Students on ScoreList.StudentId=Students.StudentId where ClassId=1 7 print 'C#平均成績:'+convert(varchar(20),@cAvg) 8 --判斷成績 9 if(@cAvg>=80) 10 print '軟體一班成績優秀!' 11else 12 print '軟體一班成績一般!'
while
1 use StudentManageDB 2 go 3 print '加分之前的C#成績:' 4 select StudentId,CSharp from ScoreList 5 declare @CSharp int,@StuId int 6 while(1=1) 7 begin 8 select top 1 @CSharp=CSharp,@StuId=StudentId 9 from ScoreList where CSharp<60 10 if (@CSharp<60) 11 update ScoreList set CSharp=CSharp+1 12 where StudentId=@StuId 13 if((select count(*) from ScoreList where CSharp<60)=0) 14 break 15 end 16 print '加分之後的C#成績:' 17 select StudentId,CSharp from ScoreList
case when
1use StudentManageDB 2 go 3 select 學號=StudentId, 4 總評=CASE 5 when (CSharp+SQLServerDB)/2>=90 then 'A' 6 when (CSharp+SQLServerDB)/2 between 80 and 89 then 'B' 7 when (CSharp+SQLServerDB)/2 between 70 and 79 then 'C' 8 when (CSharp+SQLServerDB)/2 between 60 and 69 then 'D' 9 else '不及格' 10 end 11 from ScoreList