1、批处理
/*--------------------------------------------批 处 理-----------------------------------------------------*/
-- GO --可以使不在同一批处理中的sql语句相互之间不受影响
--把相互联系的放在同一批次,没联系的放在不同批次
--批处理中某一条语句出现编译错误时,其他语句不受影响
create table T
(
id int primary key identity(1,1)
)
create table t1
(
id int references T(tid) --出错了
)
go
create table t2
(
id int references T(id) --不受影响部范围内有效
--使用变量
--找王五学号前后的同学
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
--注意:使用select 进行赋值时如果查询到的是一个结果集 那么变量得到的值是最后一条记录
--查询表中学号最小的学生姓名。
declare @stuname varchar(20)
select @stuname = stuname from StuInfo order by stuid desc
print @@error --错误代号
print @stuname
/*--全局变量--*/
①全局变量必须以@@作为前缀
②只能读取,不能修改
③全局变量在整个SQL环境下都可以被访问或调用
--if(条件)
-- begin
-- T-SQL语句
-- end
--else if (条件)
-- begin
-- T-SQL语句
-- end
--else
-- begin
-- T-SQL语句
-- end
---统计男生的平均成绩和女生的平均成绩
declare @avgman float
declare @avggirl float
select @avgman=avg(score) from StuMarks,StuInfo where StuInfo.stuid=StuMarks.stuid and
stusex='男'
select @avggirl=avg(score) from StuMarks,StuInfo where StuInfo.stuid=StuMarks.stuid and
stusex='女'
if (@avgman>@avggirl)
begin
print '男生优于女生'
--获取男生第一名的成绩
select top 1 sum(score) as '总分',StuInfo.stuid,stuname from StuMarks
,StuInfo where StuInfo.stuid=StuMarks.stuid and stusex='男'
group by StuInfo.stuid,stuname order by '总分' desc
end
else if(@avgman<@avggirl)
begin
print '女生优于男生'
--获取男生第一名的成绩
select top 1 sum(score) as '总分',StuInfo.stuid from StuMarks ,StuInfo
where StuInfo.stuid=StuMarks.stuid and stusex='女'
group by StuInfo.stuid order by '总分' desc
end
else
begin
print '男女平等'
end
--2.CASE-END语句
--CASE
-- WHEN 条件1 then 结果1
-- WHEN 条件2 then 结果2
-- [ELSE 结果]
--END
--成绩分等级
select stuname as 姓名,成绩 = 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'
/*--循环控制语句--*/
--while(循环控制条件)
-- begin
-- T-SQL语句
-- end
declare @mark int,@markid int
select @mark = score,@markid = StuMarksno from StuMarks where subject = 'html'
while @mark < 90
begin
update StuMarks set score = @mark+1 WHERE StuMarksno = @markid
select @mark = score,@markid = StuMarksno from StuMarks where subject = 'html'
end
print @score --90