Click here to Skip to main content
15,881,709 members
Articles / Database Development / SQL Server
Alternative
Tip/Trick

Traverse an MSSQL Table without using CURSOR

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
26 Aug 2012CPOL 14.8K   1   2
This is an alternative for "Traverse a MSSQL table without using CURSOR"

Introduction

The problem with the above tip is that it involves the modification of the underlying table schema. A better solution would be to run the traversal over the designed table schema, utilising the primary key value as a traversal key.

The following tip requires a sortable primary key.

Table Creation

SQL
if object_id('dbo.SomeTable', 'U') is not null
    drop table dbo.SomeTable;
    
create table dbo.SomeTable
(
     id     int identity(1, 1) not null primary key  - Used as Traversal Key
    ,Value  int not null
); 

Traversal Code

SQL
declare @id int = 0;  -- Initialised to a value smaller than the initial traversal key value.

while exists (select top 1 id from SomeTable where id > @id)
begin
    declare @value  int;
    
    select top 1 
         @value = value
        --,OtherFields
        ,@id = id
    from SomeTable
    where id > @Id
    order by id;

    -- Do something with @value and other fields.

    print @value;
end 

The benefit of this means you are no longer modifying the underlying schema of the table, and because of the sort operation, you can use any field as the traversal key.

The only requirement is that the traversal key must be unique.

Simple Table Population Code

SQL
insert into SomeTable (Value)
values
 (4) 
,(8)
,(1) 

License

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


Written By
Software Developer (Senior)
Australia Australia
Applications developer specialising in .Net, Sql technologies, web development (TypeScript/JavaScript, MVC, WebAPI, REST), data processing.

Comments and Discussions

 
GeneralMy vote of 5 Pin
ke4vtw27-Aug-12 4:52
ke4vtw27-Aug-12 4:52 
GeneralRe: My vote of 5 Pin
John B Oliver27-Aug-12 11:31
John B Oliver27-Aug-12 11:31 

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.