Theme Graphic
Theme Graphic

Jonesy's Great Code Archive

This is for me, not you. But I hope you find it useful none-the-less. Suggestions or general comments are appreciated.
Posted on Wednesday, August 26, 2009 at 10:53 AM

How to iterate through all rows in a table (MSSQL)

First we need to setup a row counter and a row max. In this example I'm iterating through a table of coupons.

DECLARE @RowCounter int
DECLARE @RowMax int
SET @RowCounter = 1
SET @RowMax = (SELECT COUNT(*) FROM Coupon)


And this is how the while loop is created

WHILE (@RowCounter <= @RowMax)
BEGIN
	-- Here you could enter real logic to process, I am just printing the RowCounter.
	PRINT 'This is row ' + CAST(@RowCounter as nvarchar(10))
	-- The RowCounter must be incremented each time to ensure the loop continues on.
	SET @RowCounter = @RowCounter + 1
END
Comments: 0 Tags: loop, MSSQL, Count

 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.