SQL Server数据库开发(2.T-Sql编程)

一,批处理(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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值