--在sql语句中 begin...end 用来设定一个程序块 相关于c#中的{} declare @yz real,@w int --声明变量 set @w=120 --为变量赋值 if @w<=100 --if条件语句 begin --Begin程序块 set @yz=@w*0.12 --为变量赋值 end else begin set @yz=100*0.12+(@w-100)*0.05 end /*输出邮件的重量和邮费*/ print '邮件的重量是:'+cast(@w as varchar(20))+'克' print '邮费是:'+cast(@yz as varchar(20))+'元' -- if-else在数据库查询的应用 declare @x int set @x =1000 if @x>950 begin set @x=@x+1000 select * from 职工 where 工资>@x end else begin set @x=@x-50 select * from 仓库 where 面积<@x END -- if...else if ...多条件判断 declare @hyuser varchar(50) ,@hypwd varchar(50),@msg varchar(50) select @hyuser='liping' , @hypwd='111' if @hyuser='hystu1' begin if @hypwd='111' set @msg='用户名与密码正确,成功登录!' else set @msg='密码不正确,请重新输入!' end else if @hyuser='hystu2' begin if @hypwd='222' set @msg='用户名与密码正确,成功登录!' else set @msg='密码不正确,请重新输入!' end else if @hyuser='hystu3' begin if @hypwd='333' set @msg='用户名与密码正确,成功登录!' else set @msg='密码不正确,请重新输入!' end else set @msg='用户名不正确,请重新输入!' print @msg --if...else...登陆判断 declare @hyuser varchar(50) ,@hypwd varchar(50),@msg varchar(50) select @hyuser='stu1' , @hypwd='111' if exists(select * from hyuser where hyname=@hyuser ) begin if exists(select * from hyuser where hyname=@hyuser and hypwd=@hypwd ) set @msg='用户名与密码都正确,成功登录!' else set @msg='密码不正确,请重新输入!' end else set @msg='用户名不正确,请得新输入!' print @msg --case when 多条件判断 declare @cj float,@str varchar(60) set @cj=90 set @str= case when @cj>100 or @cj<0 then '你输入的成绩不对,成绩应在0-100之间' when @cj>=60 and @cj<70 then '及格' when @cj>=70 and @cj<80 then '中等' when @cj>=80 and @cj<90 then '优良' when @cj>=90 and @cj<=100 then '优秀' else '不及格' end print '该学生的成绩评语:' + @str --查询不同仓库的平均工资 select * , 不同仓库的平均工资 = case when 仓库号='wh1' then (select avg(工资) from 职工 where 仓库号='wh1') when 仓库号='wh2' then (select avg(工资) from 职工 where 仓库号='wh2') when 仓库号='wh3' then (select avg(工资) from 职工 where 仓库号='wh3') when 仓库号='wh4' then (select avg(工资) from 职工 where 仓库号='wh4') end from 职工 --利用循环语句 while计算1-120相加总和 declare @x int, @sum int --声明变量 select @x=0,@sum=0 --为变量赋值 while @x<=120 --While循环语句 begin --程序块的开始 set @sum=@sum+@x set @x=@x+1 end --程序块的结构 --利用print进行输出 print '从1加120之和是:'+ cast(@sum as varchar(50)) --跳转语句 break --求从1加到10的和 但如果求得的和大于30 则跳出 declare @x int, @sum int select @x=0,@sum=0 while @x<=10 begin set @x=@x+1 set @sum=@sum+@x if @sum>30 break end waitfor delay '00:00:01' print '等1秒后输出' print '最后结果是:'+ cast(@sum as varchar(50)) --跳转语句 continue --求1-120之间所有偶数的和 declare @x int, @sum int select @x=0,@sum=0 while @x<=120 begin set @x=@x+1 if @x%2=1 continue set @sum=@sum+@x end print '从1加120所有偶数之和是:'+ cast(@sum as varchar(50)) --跳转语句 goto --利用goto求1-100之间的和 declare @x int,@sum int set @x=0 set @sum=0 bz: set @x=@x+1 set @sum=@sum+@x while @x<100 goto bz print '利用Goto语名求从1加到100的和:'+ cast(@sum as varchar(50)) --跳转语句 return --创建自定义函数 计算奖金 create function myfun(@x int) returns int as begin declare @y int set @y=@x*0.15 return @y END select *,dbo.myfun(工资) as 奖金 from 职工