Click here to Skip to main content
11,721,385 members (81,299 online)
Click here to Skip to main content

Tagged as

Traverse a MSSQL table without using CURSOR

, 3 Aug 2012 CPOL 6.4K 5
Rate this:
Please Sign up or sign in to vote.
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.
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)

Share

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.

You may also be interested in...

Comments and Discussions

 
Questionwhat for? Pin
spiralni3-Aug-12 3:07
memberspiralni3-Aug-12 3:07 
AnswerRe: what for? Pin
Abdul Quader Mamun3-Aug-12 3:15
memberAbdul Quader Mamun3-Aug-12 3:15 
GeneralRe: what for? Pin
PIEBALDconsult3-Aug-12 6:30
memberPIEBALDconsult3-Aug-12 6:30 
AnswerRe: what for? Pin
John B Oliver26-Aug-12 12:34
memberJohn B Oliver26-Aug-12 12:34 
QuestionShort note Pin
Member 29250112-Aug-12 22:22
memberMember 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 | Terms of Use | Mobile
Web04 | 2.8.150901.1 | Last Updated 3 Aug 2012
Article Copyright 2012 by Abdul Quader Mamun
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid