全局变量的总结

  很开心我们今天学习了SQL编程的全局变量,那么什么是全局变量呢?全局变量的作用是什么呢?全局变量都有哪些呢?语法又是什么呢?下面让我们简单的来了解一下SQL编程的全局变量。。在SQL-Server中的所有全局变量都使用两个@符号作为前缀,较为重要的变量为如下五个- - -

      全局变量:程序员不会自己定义全局变量,一般使用系统现有的全局变量。 

      @@ERROR        含义:(非常重要的!!原老师说的嚄!!获取最后一个T-SQL错误的错误号一般用@@Error捕获约束错误,而不是SQL语句本身的语法错                    误。当我们在面对一些复杂的业务流程的时候,一条单个的SQL语句已经无法满足需要,所以我们要将一堆SQL语句封装成一个存储过程。该                        存储过程中,可能有多个增删改操作。如

 

                       果其中某一个操作由于违反约束,造成执行失败,那么我们就需要将存储过程中所有的全部操作一次性回滚,这个时候@@Error就起到了至                        关重要的作用。每执行一个操作就获取一下@@Error的值,到最后,看@@Error的值是否大于,如果大于,就证明其中某一个环节(操作)出                        现错误,要整体回滚。!!!

 

      @@IDENTITY       含义:最后一次插入的标识值

select * from grade

insert into grade values('S2223')

select @@identity

 

 

      @@ROWCOUNT       含义:受上一个SQL语句影响的行数  select @@SERVERNAME

 

      @@SERVERNAME      含义:本地服务器的名称      

 

      @@VERSION       含义:SQL Server的版权信息  

update student set gender='QWER' 

where studentno=23

 

 

  经验:Microsoft提供的SQL Server帮助文档建议程序员使用SET语句为局部变量赋值,其原因是SET语句执行没有结果集,占用资源少。因此给一个变量赋值时,使用SET语句比使用SELECT语句的效率要高。

 

  然而局部变量的赋值有两种方法,set语句和select语句

set @ Variable_name = value   select @Variable_name - value

 

一道SQL语句面试题,关于group by

表内容:

2005-05-09 

2005-05-09 

2005-05-09 

2005-05-09 

2005-05-10 

2005-05-10 

2005-05-10 

 

如果要生成下列结果该如何写sql语句?

 

     日期       胜   负

2005-05-09       2    2

2005-05-10       1    2

------------------------------------------

*/

 

create table tmp(rq varchar(10),shengfu nchar(1))

select * from tmp

 

insert into tmp values('2005-05-09','')

insert into tmp values('2005-05-09','')

insert into tmp values('2005-05-09','')

insert into tmp values('2005-05-09','')

insert into tmp values('2005-05-10','')

insert into tmp values('2005-05-10','')

insert into tmp values('2005-05-10','')

select * from tmp

 

select rq as 日期,sum

(case 

   when shengfu='' then 1 

   else 0 

end) as 胜,sum

(

  case

    when shengfu='' then 1 

    else 0

  end

) as 负

from tmp

group by rq

  

 

经典while循环加分题目

检查学生oop”最近一次考试是否有不及格(60分及格)的学生。

如有,每人加2分,高于95分的学生不再加分,直至所有学生这次考试成绩均及格

 

科目编号

select * from result

declare @subid int

select @subid=subjectid from subject

where subjectname='oop'

 

最近一次考试时间

declare @mydate datetime

select @mydate=max(examdate) from result

where subjectid=@subid

 

不及格人数

declare @num int

select @num=count(1) from result

where subjectid=@subid

and examdate=@mydate

and studentresult<70

 

 

while(@num>0)  有成绩低于分的学员

begin

  每个人+2分,但是分以上不加分

  update result set studentresult+=2

  where studentresult<95

  and subjectid=@subid

  and examdate=@mydate

  

select @num=count(1) from result

where subjectid=@subid

and examdate=@mydate

and studentresult<70

print @num

  

end

 

select * from result

order by subjectid,examdate

 

posted @ 2016-03-07 15:05  北城以北冬季飘雪  阅读(290)  评论(0)    收藏  举报