S2第3章 T-SQL编程与高级查询

1.T-SQL中的注释

  (1)嵌入行内的注释语句:使用两个连字符(--)来表示,作用是使某一行语句无效

  (2)块注释语句:在注释文本的起始处输入"/*",在结束时输入"*/"

2.T-SQL中的批处理:批处理最明显的标志是语句末尾添加了"GO"

3.声明T-SQL局部变量和为其赋值

 

// 声明局部变量的语法
--declare {@变量名 数据类型 [,...n]} 
declare @mycounter int//示例
declare @name nvarchar(20),@age int,@address nvarchar(50)//声明多个局部变量

//为局部变量赋值的语法
--set @变量名=set @name='张三'
//或者用select为局部变量赋值
--select @变量名=select @name='张三

--两者的区别在于set只能赋值一种,而select可以赋值多个,并且select赋值时一般配合查询
--如:
set @mycount=1
set @age=18
set @address='重庆市沙坪坝区'
--而select可以写成
select @mycount=1,@age=18,@address='重庆市沙坪坝区'
select @cardId=cardId from cardInfo where cardnumber='023-002'//配合查询赋值

4.输出语句:使用print和select语句。用print输出的是文本形式,select输出的是网格形式。

5.T-SQL的流程控制

  (1)if...else语句:中间的语句块使用begin和end关键字,例:

if(条件表达式)
begin
--语句
end
else
begin
--语句
end

  (2)case语句:

select pcid as '编号',
   case pcuse
        when 0 then '空闲'
        when 1 then '正在使用'
        else ''
   end as '状态',pconte as '备注' from pcInfo
go
//或者
select sno as '学号',sname as '姓名',
   case
       when smark>=90 then '优秀'
       when smark>=80 then '良好'
       when smark>=70 then '中等'
       when smark>=80 then '及格'
       when smark>=80 then '不及格'
       else '未参与考核'
   end as '成绩等级' from score
go

  (3)while语句

while 布尔表达式
       {语句或语句块}
         [break]
       {语句或语句块}
         [continue]
       {语句或语句块}
//定义语句块时,也需要使用begin和end将语句括起来

6.子查询

(1)使用比较运算符(=、<>、>、>=、<、!>、!<或<=)的子查询,使用这些运算符的子查询必须返回单个值。

(2)IN 和 NOT IN子查询:可以返回多个值

select * from cardInfo 
  where cardid in(select cardid from recordInfo
                   where begintime<'2009-06-17' and endtime>'2009-06-16')
go

(3)EXISTS 和 NOT EXISTS子查询

select * from recordInfo
  where exists(select * from cardInfo 
                where cardid=recordInfo.cardid and cardnumber='023-002')
go
//where后面没有指定列名

 

 

 

  

 

posted @ 2013-05-07 19:49  mmww  阅读(152)  评论(0)    收藏  举报