北大青鸟第二期 第三章SQL编程 使用变量和if-else

 1 --声明变量
 2 declare @age int
 3 declare @name varchar(20)
 4 
 5 
 6 --赋值(常量值)
 7 set @age=18
 8 select @name='张三'
 9 
10 
11 --从数据库查出来并赋值
12 set @name=(select StudentName from  Student where StudentNo=10000)
13 print @name
14 select @name=StudentName from  Student where StudentNo=10000
15 print @name
16 go
17 
18 
19 --查找李文才相邻学号的学生
20 
21 
22 --1.找到李文才的学号
23 declare @StuNo int
24 select @StuNo=StudentNo from Student where StudentName='李文才'
25 print @StuNo
26 --2.李文才相邻学号的学生
27 select * from Student where StudentNo=@StuNo+1 or StudentNo=@StuNo-1
28 go
29 
30 
31 --set 和 select 区别
32 declare @address varchar(20)
33 --当查询语句返回多个值,set报错,select保留最后一个值
34 select @address=Address from Student
35 print @address
36 go
37 
38 
39 
40 
41 print '本地服务器的名称:'+@@servername
42 print 'sql的版本:'+@@version
43 
44 
45 select @@servername as '本地服务器的名称'
46 select @@version as 'sql的版本'
47 go
48 
49 
50 declare @StuNo int,@name varchar(20),@date datetime,@SubNo int,@score int
51 set @StuNo=10000   --学号赋值
52 set @date='2013-2-17'   --日期赋值
53 --根据学号查姓名
54 select @name=StudentName from Student where StudentNo=@StuNo
55 --根据科目名称查科目号
56 select @SubNo=SubjectNo from Subject where SubjectName='java Logic'
57 --根据条件查询成绩
58 select @score=StudentResult from Result where StudentNo=@StuNo and SubjectNo=@SubNo and ExamDate=@date
59 print '姓名是:'+@name
60 print '成绩是:'+convert(varchar(20),@score)
61 print '成绩是:'+cast(@score as varchar(20))
62 go
63 
64 
65 --查询学号为20012学生的java考试成绩
66 declare @stuno int,@subno int,@score int
67 set @stuno=20012
68 select @subno=SubjectNo from Subject where SubjectName='java Logic'
69 
70 
71 select @score=StudentResult from Result where StudentNo=@stuno and SubjectNo=@subno
72 print '20012java成绩为:'+convert(varchar(20), @score)
73 go
74 
75 
76 --if-else
77 --查询java Logic的科目编号
78 declare @subno int,@date datetime,@avg decimal(5,2)
79 set @date='2013-2-17' --时间
80 select @subno=SubjectNo from Subject where SubjectName='java Logic'
81 print @subno
82 --查询2013-2-17java考试的平均分
83 select @avg=avg(StudentResult) from Result where ExamDate=@date and SubjectNo=@subno
84 
85 
86 if(@avg>=70)
87 begin
88 print '成绩优秀'
89 end
90 else
91 begin
92 print '成绩较差'
93 end

 

posted @ 2017-09-13 13:24  XLcker  阅读(260)  评论(0编辑  收藏  举报