Click here to Skip to main content
15,886,422 members
Articles / Database Development / SQL Server
Alternative
Article

Traverse a MSSQL table without using CURSOR

Rate me:
Please Sign up or sign in to vote.
2.71/5 (3 votes)
3 Aug 2012CPOL 13.3K   4   4
This is an alternative for "Traverse a MSSQL table without using CURSOR"

Introduction

The original tip avoided the use of cursors, but in exchange, used table row modifications inside of a transaction. This leads to its own share of problems.

Ideally, traversing the rows in a table would require nothing but table reads. This tip shows one way to accomplish this. 

Using the code 

I'll use the same table structure as the original tip:

SQL
CREATE TABLE [dbo].[A](
    [Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
    [Value] [int] NOT NULL,
    [Flag] [bit] NULL ) 

In addition to traversing an entire table, this method allows us to specify a contiguous subset of the table to traverse if desired.  To begin, set the value of the @Id variable to one less than the first item. This is important; we get the next item in the list at the top of the loop, so this ensures that we don't skip the first item.

Secondly, set the value of @LastID to the id of the last item to be processed.

Code your task after the "--code here" comment, and you're ready to go.  

SQL
BEGIN TRY    
 
    BEGIN TRANSACTION
 
    DECLARE @Id INT, @LastID INT    
    SELECT @Id = MIN([Id])-1 FROM A
    SELECT @LastId = MAX([Id])-1 FROM A
        
    WHILE  @Id <= @LastID
        BEGIN      
            --Get the next item in the list 
            SELECT TOP 1 @Id=[Id] FROM A WHERE [Id] > @Id ORDER BY [Id]  
            
             --code here            
             PRINT @id
                              
        END
 
    COMMIT TRANSACTION    
    
END TRY
BEGIN CATCH
 
    ROLLBACK TRANSACTION
    RAISERROR ('Error, Please try again.',16,1)
        
END CATCH

Enjoy!

History

8/3/2012: Original submission.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
RedDk13-Jul-15 7:22
RedDk13-Jul-15 7:22 
GeneralRe: My vote of 1 Pin
ke4vtw29-Jan-16 8:57
ke4vtw29-Jan-16 8:57 
AnswerStill uses the cursor Pin
RAND 4558661-Jan-15 6:27
RAND 4558661-Jan-15 6:27 
GeneralRe: Still uses the cursor Pin
ke4vtw2-Jan-15 8:07
ke4vtw2-Jan-15 8:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.