一,批处理(GO)
--可以使不在同一批处理中的sql语句相互之间不受影响
--把相互联系的放在同一批次,没联系的放在不同批次
二,变量分类(局部变量。全局变量)
2.1局部变量
先声明变量
declare@变量名 数据类型
declare@id char (10) --声明一个长度为个字符的变量id
declare@age int --声明一个存放职员年龄的整型变量
然后变量赋值
--set@变量名 = 值 :用于普通的赋值
set@age = 20
--select@变量名 = 值:用于从表中查询数据并赋值
select@id = '11111'
在使用变量
列。 找王五学号前后的同学
declare @sid int
select @sid = stuid from StuInfo where stuname='王五'
print '王五的学号为:' + convert(varchar(20),@sid)
select * from StuInfo where stuid=@sid-1 or stuid=@sid+1
局部变量只在定义它的局部输入范围内有效
2.2全局变量
是以@@全局变量名
由系统定义和维护,只读不能改
全局变量在整个SQL环境下都可以被访问或调用
三,分支结构
IF-ELSE语句
--if(条件)
-- begin
-- T-SQL语句
-- end
--else if (条件)
-- begin
-- T-SQL语句
-- end
--else
-- begin
-- T-SQL语句
-- end
--1.查找出王五前后学生
declare @name varchar(10),@age int,@nameone varchar(10),@nametwo varchar(10)
select stuid from StuInfo where stuName='王五'
select @name=stuName from StuInfo where stuid=3
select @nameone=stuName from StuInfo where stuid=3+1
select @nametwo=stuName from StuInfo where stuid=3-1
select @name
select @nameone
select @nametwo
--2.比较男女平均成绩的优异
declare @nan int,@nv int
select @nan=AVG(score) from StuInfo,StuMarks where StuInfo.stuid=StuMarks.stuid and stusex='男'
select @nv=AVG(score) from StuInfo,StuMarks where StuInfo.stuid=StuMarks.stuid and stusex='女'
if(@nan>@nv)
begin
print'男生成绩优异'
end
else
print'女生成绩优异'
--3.给分数分等级制度
select stuName,score,等级=
case
when score>=90 then 'A'
when score>=80 then 'B'
when score>=70 then 'C'
when score>=60 then 'D'
else 'E'
end
from StuInfo,StuMarks
where StuInfo.stuid=StuMarks.stuid and subject='SQL'
--4.把一个学生成绩依次相加修改到70
declare @score1 int
select @score1=score from StuMarks where StuMarksno=6
while (@score1<70)
begin
set @score1=@score1+1
update StuMarks set score = @score1 where StuMarksno=6
end
print @score1