Click here to Skip to main content
15,888,802 members
Articles / Database Development / SQL Server
Tip/Trick

Traverse a MSSQL table without using CURSOR

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
3 Aug 2012CPOL 12.6K   5   5
To traverse a table without cursor, you only need to add an additional field in the table with null value. Here is the code for traversing a table.
Table structure here. In my case Flag is the additional field which contains null value.
C#
CREATE TABLE [dbo].[A](
	[Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
	[Value] [int] NOT NULL,
	[Flag] [bit] NULL
) 

Here is the code for traversing

SQL
BEGIN TRY	

	BEGIN TRANSACTION

	DECLARE @Id int	
		
	WHILE  EXISTS(SELECT TOP 1 * FROM A WHERE Flag IS null)
		BEGIN	
		     --code here
			
		     SELECT TOP 1 @Id=ID FROM A WHERE Flag IS null	
		     UPDATE A WITH (TABLOCK) SET Flag=1 WHERE Id=@Id
		END

	UPDATE A  WITH (TABLOCK) SET Flag=null	
	COMMIT TRANSACTION	
	
END TRY
BEGIN CATCH

	ROLLBACK TRANSACTION
	RAISERROR ('Error, Please try again.',16,1)
		
END CATCH

License

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


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

Comments and Discussions

 
Questionwhat for? Pin
spiralni3-Aug-12 3:07
spiralni3-Aug-12 3:07 
AnswerRe: what for? Pin
Abdul Quader Mamun3-Aug-12 3:15
Abdul Quader Mamun3-Aug-12 3:15 
GeneralRe: what for? Pin
PIEBALDconsult3-Aug-12 6:30
mvePIEBALDconsult3-Aug-12 6:30 
AnswerRe: what for? Pin
John B Oliver26-Aug-12 12:34
John B Oliver26-Aug-12 12:34 
QuestionShort note Pin
Member 29250112-Aug-12 22:22
Member 29250112-Aug-12 22:22 

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.