Click here to Skip to main content
Click here to Skip to main content

Traverse a MSSQL table without using CURSOR

By , 3 Aug 2012
Rate this:
Please Sign up or sign in to vote.
Table structure here. In my case Flag is the additional field which contains null value.
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

  
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)

About the Author

Abdul Quader Mamun
Team Leader
Bangladesh Bangladesh
I have been developing software/web applications since 2002 mainly on Microsoft technologies.
 
I'm also experienced with other technologies.
 
I'm fan of well organized and effective coding.
 
A wide range of technologies, tools, languages, frameworks, components and design patterns I’m experienced with.
 
I’m a MCP, MCAD.NET, MCSD.NET.
Follow on   Google+

Comments and Discussions

 
Questionwhat for? Pinmemberspiralni3-Aug-12 3:07 
AnswerRe: what for? PinmemberAbdul Quader Mamun3-Aug-12 3:15 
GeneralRe: what for? PinmemberPIEBALDconsult3-Aug-12 6:30 
AnswerRe: what for? PinmemberJohn B Oliver26-Aug-12 12:34 
QuestionShort note PinmemberMember 29250112-Aug-12 22:22 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140421.2 | Last Updated 3 Aug 2012
Article Copyright 2012 by Abdul Quader Mamun
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid