1. Cursors are easy to use when the data table does not have id(identity(1,1)), but cursors will consume more memory, reduce available concurrency, occupy bandwidth, lock resources, and of course require more code.
2. If you can do without a cursor, try not to use it. Be sure to close and release it after use. Try not to define a cursor on a large amount of data. Try not to use a cursor to update data.
Cursor:Global for--global cursor
Cursor:Local for--local cursor
LOCAL means that the lifetime of the cursor is only visible within the batch or function or stored procedure
GLOBAL means that the cursor is valid globally for a specific connection as context
- --Step 1: Declare the cursor
- declare test_Cursor Cursor scroll for
- select name from dbo.aa
- open test_Cursor--Open the cursor
- --Second execution
- declare @name nvarchar(1000)
- fetch next from test_Cursor into @name--next line
- select @name
- --Close and clear the cursor for the third time
- CLOSE test_Cursor--Close
- DEALLOCATE test_Cursor--Clear
- /*Only supports 6 movement options, namely to the first row (FIRST),
- Last line (LAST), next line (NEXT), previous line (PRIOR),
- Jump directly to a certain line (ABSOLUTE(n)),
- Jump a few lines relative to the current one (RELATIVE(3))*/
Loop data through cursor
- 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
- --Last execution
- CLOSE test_Cursor
- DEALLOCATE test_Cursor