SQL语句提供了对记录集合的各种操作,但若需要进行一些针对记录集中的单个记录进行
判断,然后再执行的操作,有时就不能实现,而使用游标可以解决这一1问题:
1:游标的创建和使用
游标的创建分为5个步骤:
(1)定义游标:( 查下语法规则)
ex:
declare T_log_cursor CURSOR
FOR
SELECT ID,F_logText,F_logType,datee from dbo.T_log
where F_logType='3' order by datee
(2) 打开游标:
--2打开游标,实际上执行定义游标内的select语句,形成游标记录集填充游标,并把游标的指针定位在第一条记录前
open T_log_cursor
declare @cur_rowcount int
select @cur_rowcount=@@CURSOR_ROWS
print @cur_rowcount
(3)读取游标
--读取游标(fetch cursor)
declare @id int
declare @F_logType nvarchar(50)
declare @F_logText nvarchar(50)
declare @datee Datetime
fetch next from T_log_cursor
into @id,@F_logText,@F_logType,@datee --将记录各字段内容保存到对应的变量中
while @@FETCH_STATUS=0
begin
print (str(@id)+''+@F_logText+''+@F_logType+''+Convert(nvarchar,@datee))
fetch next from T_log_cursor
into @id,@F_logText,@F_logType,@datee
end
(4) 关闭游标
close T_log_cursor
(5) 释放游标
deallocate T_log_cursor
一个连贯的句子就是:
select * from dbo.T_log
--1定义游标
declare T_log_cursor CURSOR
FOR
SELECT ID,F_logText,F_logType,datee from dbo.T_log
where F_logType='3' order by datee
--2打开游标,实际上执行定义游标内的select语句,形成游标记录集填充游标,并把游标的指针定位在第一条记录前
open T_log_cursor
--3读取游标(fetch cursor)
declare @id int
declare @F_logType nvarchar(50)
declare @F_logText nvarchar(50)
declare @datee Datetime
fetch next from T_log_cursor
into @id,@F_logText,@F_logType,@datee --将记录各字段内容保存到对应的变量中
while @@FETCH_STATUS=0
begin
print (str(@id)+''+@F_logText+''+@F_logType+''+Convert(nvarchar,@datee))
fetch next from T_log_cursor
into @id,@F_logText,@F_logType,@datee
end
--4关闭游标
close T_log_cursor
--5释放游标
deallocate T_log_cursor
3:游标使用中应注意的问题:
(1) 全局变量:
全局变量@@fetch_status 用来存储fetch语句执行状态的信息,可使用查询语句
select @@fetch_status 来完成上述查询任务。
全局变量@@rowcount记载到最近一次fetch操作为止,从游标记录集中共返回的行数,同样,可
使用查询语句select @@rowcount 来进行查看:
游标的使用会在几个方面影响系统的性能:
导致页锁和表锁的增加;
导致网络通信量的增加
服务器处理相应指令的额外开销:
因此尽管游标控制比较灵活,但会损失速度,这就存在一个游标使用的优化: