SQL Cursor(cursor)

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

 
  1. --Step 1: Declare the cursor
  2. declare test_Cursor Cursor scroll for
  3. select name from dbo.aa
  4. open test_Cursor--Open the cursor
  5. --Second execution
  6. declare @name nvarchar(1000)
  7. fetch next from test_Cursor into @name--next line
  8. select @name
  9. --Close and clear the cursor for the third time
  10. CLOSE test_Cursor--Close
  11. DEALLOCATE test_Cursor--Clear
  12. /*Only supports 6 movement options, namely to the first row (FIRST),
  13. Last line (LAST), next line (NEXT), previous line (PRIOR),
  14. Jump directly to a certain line (ABSOLUTE(n)),
  15. Jump a few lines relative to the current one (RELATIVE(3))*/

Loop data through cursor

 
  1. declare test_Cursor Cursor scroll for
  2. select id,materialName from dbo.table_1
  3.  
  4. open test_Cursor
  5. declare @c nvarchar(10)
  6. declare @name nvarchar(1000)
  7.  
  8. while @@FETCH_STATUS=0
  9. begin
  10. fetch next from test_Cursor into @c,@name
  11. select @c,@name
  12. end
  13. --Last execution
  14. CLOSE test_Cursor
  15. DEALLOCATE test_Cursor

Guess you like

Origin blog.csdn.net/ole_triangle_java/article/details/105550264