Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

ADO like Cursor operations using T-SQL

Total Hit ( 1764)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


This article shows how to use SQL cursor to perform MoveFirst, MoveLast, MoveNext, MovePrev and MoveAbsolute operations using T-SQL's SCROLL CURSOR

Click here to copy the following block
USE pubs
GO

Declare @au_lname varchar(100)
Declare @au_fname varchar(100)

-- Execute the SELECT statement alone to show the
-- full result set that is used by the cursor.
SELECT au_lname, au_fname FROM authors
ORDER BY au_lname, au_fname


-- Declare the cursor.
DECLARE authors_cursor SCROLL CURSOR FOR
SELECT au_lname, au_fname FROM authors
ORDER BY au_lname, au_fname

OPEN authors_cursor

Print '**** Loop through records ****'    
FETCH NEXT FROM authors_cursor into @au_lname ,@au_fname
WHILE @@FETCH_STATUS=0
Begin
   Print @au_lname + ', ' + @au_fname    
   FETCH NEXT FROM authors_cursor into @au_lname ,@au_fname
End

-- Fetch the last row in the cursor.
Print '**** Fetch the last row in the cursor ****'
FETCH LAST FROM authors_cursor into @au_lname ,@au_fname
Print @au_lname + ', ' + @au_fname

-- Fetch the row immediately prior to the current row in the cursor.
Print '**** Fetch the row immediately prior to the current row in the cursor. ****'
FETCH PRIOR FROM authors_cursor into @au_lname ,@au_fname
Print @au_lname + ', ' + @au_fname

-- Fetch the second row in the cursor.
Print '**** Fetch the second row in the cursor. ****'
FETCH ABSOLUTE 2 FROM authors_cursor into @au_lname ,@au_fname
Print @au_lname + ', ' + @au_fname

-- Fetch the row that is three rows after the current row.
Print '**** Fetch the row that is three rows after the current row. ****'
FETCH RELATIVE 3 FROM authors_cursor into @au_lname ,@au_fname
Print @au_lname + ', ' + @au_fname

-- Fetch the row that is two rows prior to the current row.
Print '**** Fetch the row that is two rows prior to the current row. ****'
FETCH RELATIVE -2 FROM authors_cursor into @au_lname ,@au_fname
Print @au_lname + ', ' + @au_fname

CLOSE authors_cursor
DEALLOCATE authors_cursor
GO


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.