功能:
定义 Transact-SQL 服务器游标的特性,例如游标的滚动行为和用于生成游标对其进行操作的结果集的查询。DECLARE CURSOR 接受基于 SQL-92 标准的语法和使用一组 Transact-SQL 扩展的语法。
Transact-SQL 扩展语法
DECLARE cursor_name CURSOR
[ LOCAL | GLOBAL ]
[ FORWARD_ONLY | SCROLL ]
[ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ]
[ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ]
[ TYPE_WARNING ]
FOR select_statement
[ FOR UPDATE [ OF column_name [ ,...n ] ] ]
实例解释
1,删除数据库中所有表的记录
declare @sql nvarchar(200) --如果select多个字段,则可以声明多个参数值,fetch...into到多个参数值中
declare c1 cursor for --声明游标
select name from sysobjects where xtype='u' --查询所有表名
open c1 --打开游标
fetch next from c1 into @sql --读取游标值放到变量@sql中
while @@fetch_status=0 --读取游标值成功
begin
set @sql='delete '+@sql
print @sql
exec (@sql)
fetch next from c1 into @sql --读取下一个游标值
end
close c1 --关闭游标
deallocate c1--释放游标引用
2,更新表中字段值
declare @sql nvarchar(200)
declare c1 cursor for --声明游标
select contact from tb where concattype='手机'
for update--(不加of [columns]表示更新所有字段)
open c1
fetch next from c1 into @sql
while @@fetch_status=0
begin
update tb set contact='13524245252' where current of c1
fetch next from c1 into @sql
end
close c1
deallocate c1
@@FETCH_STATUS
返回被 FETCH 语句执行的最后游标的状态,而不是任何当前被连接打开的游标的状态。
0 FETCH 语句成功。
-1 FETCH 语句失败或此行不在结果集中。
-2 被提取的行不存在。