Cursor
--=============================================================================================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语句中为cursor赋值,也可以使用SET来为游标赋值;
2。LOCAL标明所定义的游标在当前上下文中可见(当前批处理/存储过程/函数中可见), GLOBAL标明所定义的游标在当前连接(SESSION)中可见,包括调用的存储过程/函数内部可见,默认时使用GLOBAL;3。FORWARD_ONLY标明定义游标只能从结果集顶部向底部移动,访问的是sTATIC结果集;SCROLL标明游标可以向任意方向移动。4。STATIC标明游标所操作的结果集为静态,执行时将结果集COPY放入TempDB中,使得后续或外部操作修改数据任然不会影响游标操作的结果集; DYNAMIC则与STATIC相反,当数据在后续操作或外部操作中被修改时,游标读取的数据是修改后的数据; KEYSET介于STATIC与DYNAMIC之间,只将游标结果集中每行的主键保存到TmepDB中; FAST_FORWAD依据上下文选择使用STATIC或DYNAMIC中一种5。READ_ONLY标明游标只读取数据而不做任何修改操作 SCROLL_LOCKS标明游标锁定结果集中数据,防止外部操作修改数据 OPTIMISTIC不会锁定结果集中数据,但当在游标中更新数据时,如果该数据没有被外部操作更新,则游标更新可能成功,反之则失败;6。使用OPEN CURSOR来打开触发器7。使用FETCH [NEXT|PRIOR|FIRST|LAST|ABSOLUTE(N)|RELATIVE(N)] FROM cursorName INTO 来获取数据;8。使用CLOSE来关闭游标9。使用DEALLOCATE来释放游标--=============================================================================================
@@FETCH_STATUS枚举值:0:The FETCH statement was successful.-1:The FETCH statement failed or the row was beyond the result set.-2: The row fetched is missing.--============================================================================================= DECLARE @userId INT;DECLARE @userName NVARCHAR(200);DECLARE myCursor CURSOR READ_ONLY FAST_FORWARD FORSELECT UserId,UserName FROM dbo.UsersOPEN myCursor
FETCH NEXT FROM myCursor INTO @userId,@userNameWHILE(@@FETCH_STATUS=0)BEGINPRINT @userNameFETCH NEXT FROM myCursor INTO @userId,@userNameENDCLOSE myCursor
DEALLOCATE myCursorSELECT COUNT(1) FROM dbo.Users
--=============================================================================================1.尽量避免使用游标2.使用完游标一定得关闭并释放3.如果可以,尽量使用只读(READ_ONLY)向前(FAST_FORWARD)游标4.避免大结果集操作