1.遊標在數據表沒有id(identity(1,1))時好用,但是遊標會吃更多的內存,減少可用的併發,佔用寬帶,鎖定資源,當然還有更多的代碼量
2.如果能不用遊標,儘量不要使用遊標,用完用完之後一定要關閉和釋放, 儘量不要在大量數據上定義遊標,儘量不要使用遊標上更新數據
Cursor:Global for--全局遊標
Cursor:Local for--局部遊標
LOCAL意味着遊標的生存週期只在批處理或函數或存儲過程中可見
GLOBAL意味着遊標對於特定連接作爲上下文,全局內有效
- --第一步:聲明遊標
- declare test_Cursor Cursor scroll for
- select name from dbo.aa
- open test_Cursor--打開遊標
- --第二遍執行
- declare @name nvarchar(1000)
- fetch next from test_Cursor into @name--下一行
- select @name
- --第三遍關閉清空遊標
- CLOSE test_Cursor--關閉
- DEALLOCATE test_Cursor--清空
- /*只有支持6種移動選項,分別爲到第一行(FIRST),
- 最後一行(LAST),下一行(NEXT),上一行(PRIOR),
- 直接跳到某行(ABSOLUTE(n)),
- 相對於目前跳幾行(RELATIVE(3))*/
通過遊標循環數據
- declare test_Cursor Cursor scroll for
- select id,materialName from dbo.table_1
- open test_Cursor
- declare @c nvarchar(10)
- declare @name nvarchar(1000)
- while @@FETCH_STATUS=0
- begin
- fetch next from test_Cursor into @c,@name
- select @c,@name
- end
- --最後執行
- CLOSE test_Cursor
- DEALLOCATE test_Cursor