Your SlideShare is downloading. ×
0
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Lecture 3. MS SQL. Cursors.

234

Published on

My lecture notes, composed from different open sources from Internet. If you have copyright claims just tell me to remove.

My lecture notes, composed from different open sources from Internet. If you have copyright claims just tell me to remove.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
234
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
12
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Database Development in SQL Server 2005Lecture 3Cursors
  • 2. Transact SQL Extensions• Database cursor is a control structure that enables traversal over therecords in a database. Cursors facilitate subsequent processing inconjunction with the traversal, such as retrieval, addition and removalof database records.• The database cursor characteristic of traversal makes cursors akin tothe programming language concept of iterator.• Cursors are used by database programmers to process individualrows returned by database system queries.• In SQL procedures, a cursor makes it possible to define a result set (aset of data rows) and perform complex logic on a row by row basis.• A cursor can be viewed as a pointer to one row in a set of rows. Thecursor can only reference one row at a time, but can move to otherrows of the result set as needed.
  • 3. Using of CursorsTo use cursors in SQL procedures, you need to do the following:• Declare a cursor that defines a result set.• Open the cursor to establish the result set.• Fetch the data into local variables as needed from thecursor, one row at a time.• Close the cursor when done.• Deallocate the cursor to freeup resources.
  • 4. Declaring CursorDECLARE <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 ] ] ]
  • 5. Declaring Cursor: scope propertiesLOCAL - Specifies that the scope of the cursor is local to the batch, storedprocedure, or trigger in which the cursor was created. The cursor nameis only valid within this scope. The cursor can be referenced by localcursor variables in the batch, stored procedure, or trigger, or a storedprocedure OUTPUT parameter. The cursor is implicitly deallocated whenthe batch, stored procedure, or trigger terminates, unless the cursorwas passed back in an OUTPUT parameter.GLOBAL - Specifies that the scope of the cursor is global to the connection.(This is the default.) The cursor name can be referenced in any storedprocedure or batch executed by the connection. The cursor is onlyimplicitly deallocated at disconnect.
  • 6. Declaring Cursor: scrollability propertiesFORWARD_ONLY - Specifies that the cursor can only be scrolled from thefirst to the last row. FETCH NEXT is the only supported fetch option.SCROLL - Specifies that the cursor can be scrolled in any direction. Thefetch options become:NEXTPRIORFIRSTLAST
  • 7. Declaring Cursor: types of cursors 1STATIC - Defines a cursor that makes a temporary copy of the data to be usedby the cursor. All requests to the cursor are answered from this temporarytable in tempdb; therefore, modifications made to base tables are notreflected in the data returned by fetches made to this cursor, and thiscursor does not allow modifications. This is not a very useful cursor…KEYSET - Specifies that the membership and order of rows in the cursor arefixed when the cursor is opened. The set of keys that uniquely identify therows is built into a table in tempdb known as the keyset. Changes tononkey values in the base tables, either made by the cursor owner orcommitted by other users, are visible as the owner scrolls around thecursor. Inserts made by other users are not visible (inserts cannot be madethrough a Transact-SQL server cursor). If a row is deleted, an attempt tofetch the row returns an @@FETCH_STATUS of -2. Keyset cursors areuseful as the basis for a cursor that will perform updates to the data. Youmust have a unique index on the table from which you take your data.
  • 8. Declaring Cursor: types of cursors 2DYNAMIC - Defines a cursor that reflects all data changes made to therows in its result set as you scroll around the cursor. The data values,order, and membership of the rows can change on each fetch. TheABSOLUTE fetch option is not supported with dynamic cursors. Theseare overhead hogs… it is best to avoid them, since they have to re-query the table on every FETCH.FAST_FORWARD - Specifies a FORWARD_ONLY, READ_ONLY cursor withperformance optimizations enabled. FAST_FORWARD cannot bespecified if SCROLL or FOR_UPDATE is also specified.FAST_FORWARD and FORWARD_ONLY are mutually exclusive; if oneis specified the other cannot be specified.
  • 9. Declaring Cursor: concurrency optionsREAD_ONLY - Prevents updates made through this cursor. The cursor cannotbe referenced in a WHERE CURRENT OF clause in an UPDATE or DELETEstatement. This option overrides the default capability of a cursor to beupdated.SCROLL_LOCKS - Specifies that positioned updates or deletes made throughthe cursor are guaranteed to succeed. SQL Server locks the rows as theyare read into the cursor to ensure their availability for later modifications.SCROLL_LOCKS cannot be specified if FAST_FORWARD is also specified.OPTIMISTIC - Specifies that positioned updates or deletes made through thecursor do not succeed if the row has been updated since it was read intothe cursor. SQL Server does not lock rows as they are read into the cursor.It instead uses comparisons of timestamp column values, or a checksumvalue if the table has no timestamp column, to determine whether the rowwas modified after it was read into the cursor. If the row was modified, theattempted positioned update or delete fails. OPTIMISTIC cannot bespecified if FAST_FORWARD is also specified.
  • 10. Declaring Cursor: FOR clause<select_statement> - Is a standard SELECT statement that definesthe result set of the cursor. The keywords COMPUTE, COMPUTEBY, FOR BROWSE, and INTO are not allowed withinselect_statement of a cursor declaration. SQL Server implicitlyconverts the cursor to another type if clauses in select_statementconflict with the functionality of the requested cursor type.UPDATE [OF column_name [,...n]] - Defines updatable columnswithin the cursor. If OF <column_name> [,...n] is supplied, onlythe columns listed allow modifications. If UPDATE is specifiedwithout a column list, all columns can be updated, unless theREAD_ONLY concurrency option was specified. This is used torestrict what columns may be updated. If this clause is omitted,all columns in the <select_statement> may be updated.
  • 11. The FETCH StatementFETCH retrieves a specific row from a Transact-SQL server cursor.FETCH[ [ NEXT | PRIOR | FIRST | LAST| ABSOLUTE { n | @nvar }| RELATIVE { n | @nvar }]FROM]{ { [ GLOBAL ] cursor_name } | @cursor_variable_name }[ INTO @variable_name [ ,...n ] ]
  • 12. FETCH Arguments 1NEXT - Returns the result row immediately following the current row,and increments the current row to the row returned. If FETCH NEXT isthe first fetch against a cursor, it returns the first row in the resultset. NEXT is the default cursor fetch option.PRIOR - Returns the result row immediately preceding the current row,and decrements the current row to the row returned. If FETCH PRIORis the first fetch against a cursor, no row is returned and the cursor isleft positioned before the first row.FIRST - Returns the first row in the cursor and makes it the current row.
  • 13. FETCH Arguments 2LAST - Returns the last row in the cursor and makes it the current row.ABSOLUTE {n | @nvar} - If n or @nvar is positive, returns the row n rows fromthe front of the cursor and makes the returned row the new current row. If nor @nvar is negative, returns the row n rows before the end of the cursor andmakes the returned row the new current row. If n or @nvar is 0, no rows arereturned.RELATIVE {n | @nvar} - If n or @nvar is positive, returns the row n rows beyondthe current row and makes the returned row the new current row. If n or@nvar is negative, returns the row n rows prior to the current row and makesthe returned row the new current row. If n or @nvar is 0, returns the currentrow.GLOBAL - Specifies that cursor_name refers to a global cursor.
  • 14. ExampleDECLARE @TableName AS varchar(255)--declaring cursorDECLARE TableCursor CURSOR FORSELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLESWHERE TABLE_TYPE=BASE TABLE--opening cursorOPEN TableCursor
  • 15. ...cont--fetching data from cursorFETCH NEXT FROM TableCursor INTO @TableNameWHILE @@FETCH_STATUS = 0BEGINPRINT Reindexing + @TableNameDBCC REINDEX(@TableName)FETCH NEXT FROM TableCursor INTO @TableNameEND--closing and deallocating cursorCLOSE TableCursorDEALLOCATE TableCursor
  • 16. Altering Data with a CursorCan alter or delete data in a table underlying a cursor by usingUPDATE or DELETE on the cursor with the WHERE CURRENT OFstatement (still use the select statement in the cursordeclaration). These are called positioned updates or deletes.-- declaring the cursor…DECLARE OrdersCursor CURSORFOR SELECT OrderID, CustomerID, OrderDate FROM OrdersWHERE OrderID < 10260 FOR UPDATE OF CustomerID
  • 17. ...cont-- an example of statements to perform a positioned update ordelete inside the processing loopDELETE Orders WHERE CURRENT OF OrdersCursorUDPATE Orders SET ShipVia=2 WHERE CURRENT OFOrdersCursor-- an example of declaring the cursor to restrict updates to theCustomerID field onlyDECLARE OrdersCursor CURSORFOR SELECT OrderID, CustomerID, OrderDate FROM OrdersWHERE OrderID < 10260 FOR UPDATE OF CustomerID

×