游标是非常邪恶的一种存在,使用游标经常会比使用面向集合的方法慢2-3倍,当游标定义在大数据量时,这个比例还会增加。如果可能,尽量使用while,子查询,临时表,函数,表变量等来替代游标,记住,游标永远只是你最后无奈之下的选择,而不是首选 使用游标的两个例子。
--定义表变量
DECLARE @temp TABLE
(
[id] INT IDENTITY(1, 1) ,
[Name] VARCHAR(10)
)
DECLARE @tempId INT ,
@tempName VARCHAR(10)
DECLARE test_Cursor CURSOR LOCAL FOR
SELECT [id],[name] FROM @temp
--插入数据值
INSERT INTO @temp
VALUES ( 'a' )
INSERT INTO @temp
VALUES ( 'b' )
INSERT INTO @temp
VALUES ( 'c' )
INSERT INTO @temp
VALUES ( 'd' )
INSERT INTO @temp
VALUES ( 'e' )
--打开游标
OPEN test_Cursor
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM test_Cursor INTO @tempId,@tempname
PRINT 'Name:----' + @tempName
END
CLOSE test_Cursor
DEALLOCATE test_Cursor
另外一个例子
1 --将book表中的LookCount(int型)字段加上800-1000的随机整数 2 declare @bid int 3 declare cur cursor 4 read_only 5 for select bid from dbo.Book 6 open cur 7 fetch next from cur into @bid 8 while(@@fetch_status=0) 9 begin 10 update dbo.Book set LookCount=LookCount+cast((rand()*(1000-800)+800) as int) where bid=@bid 11 fetch next from cur into @bid 12 end 13 close cur 14 deallocate cur