BEGIN TRY
END TRY
BEGIN CATCH
END CATCH
包括SQL Server数据类型、语言元素(批处理、注释、变量、函数、运算符、T-SQL控制流程)和游标,下面分说。
1.数据类型 :系统和 自定义 数据类型 删除 sp_droptype
2.变量: 全局变量(可测系统设定值和sql 命令执行后的状态值,引用 以@@ 开头),局部变量(declare,select set 赋值)
3批处理 go 隔开
4注释
5运算符
6函数
行集函数:当做表引用
CONTAINSTABLE(),
FREETEXTTABLE(),
OPENQUERY(),
OPENROWSET(), SELECT*FROM OPENQUERY(local, 'SELECT * FROM department')
OPENDATASOURCE(),
OPENXML();
聚合函数:用于对一组值执行计算后返回单个值(min max)
标量函数: 对一个或多个参数值处理
自定义函数(标量型函数、内嵌表值函数、多语句表值型函数)。
7流程控制语句
--获取考试成绩名次。
CREATE FUNCTION [dbo].[GetRankNum] (
@ExamID varchar(30) , --考试批次
@GradeID varchar(30), --年级ID
@ClassID varchar(30), --班级ID
@SubjectID varchar(30), --科目ID
@TestScores varchar(30), --考试分数
@Type int --查询类型(1:科目班级名次、2:科目年级名次、3:总分班级名次、4:总分年级名次)
)
RETURNS integer AS
BEGIN
END
Begin..end 、if…else、if….exists、while、case、return、waitfor、goto、print
8游标(声明、打开、读取游标数据、修删游标数据、释放游标数据)
声明游标:DECLARE 游标名称 cursor // 应该可以 加 for 语句select
打开游标:open 游标名称
读取游标:fetch 游标名称
修删游标数据:
Update table_name
Delete table_name
例子:
首先声明游标
Declare authors_curscroll cursor
For www.2cto.com
Select * from authors.for update of
Au_lname,au_fname
更新authors表中的au_name 和 au_lname列
Update authors
Set au_lname=‘china’,au_fname=‘asia’
Where current of authors_cur
删除authors表中的一行数据
Delete from authors
Where current of authors_cur
游标用完之后,我们需要关闭游标来释放修改过的数据(close、deallocate)
//游标 实例
declare cursor_t1 cursor for select distinct id from t1
declare @id int
declare @pid varchar(8000)
if object_id('t2') is not null --构造t2表的结构
drop table t2
create table t2(id int,pid varchar(8000))
open cursor_t1
fetch next from cursor_t1 into @id
while @@fetch_status = 0
begin
set @pid =''
declare @len int
select @len=count(1) from t1 where id=@id
if object_id('tempdb..#tmp') is not null --构造临时表
drop table #tmp
select identity(int,1,1) as newid,id,pid into #tmp from t1 where id=@id
while @len>0 --通过循环拼接字符串
begin
select @pid=@pid +','+cast(pid as varchar) from #tmp where [newid]=@len
set @len=@len-1
end
drop table #tmp
set @pid=right(@pid,len(@pid)-1)
insert into t2 select @id, @pid --插入结果到t2表
fetch next from cursor_t1 into @id
end
declare @id int
declare @pid varchar(8000)
if object_id('t2') is not null --构造t2表的结构
drop table t2
create table t2(id int,pid varchar(8000))
open cursor_t1
fetch next from cursor_t1 into @id
while @@fetch_status = 0
begin
set @pid =''
declare @len int
select @len=count(1) from t1 where id=@id
if object_id('tempdb..#tmp') is not null --构造临时表
drop table #tmp
select identity(int,1,1) as newid,id,pid into #tmp from t1 where id=@id
while @len>0 --通过循环拼接字符串
begin
select @pid=@pid +','+cast(pid as varchar) from #tmp where [newid]=@len
set @len=@len-1
end
drop table #tmp
set @pid=right(@pid,len(@pid)-1)
insert into t2 select @id, @pid --插入结果到t2表
fetch next from cursor_t1 into @id
end
close cursor_t1