If you find this article useful, consider making a small donation to show your support for this web site and its content.
DiscountASP
AboutMe
About me:
Hi. My name is Farooq Kaiser and I'm a software developer from Toronto, Canada.

Building a T-SQL Loop

by Farooq Kaiser 12. June 2009 14:04

This topic shows how to write Nested loop with table variable instead of cursors. This tutorial will use AdventureWorks database. 

DECLARE @COUNTER AS INT
 DECLARE @TOTALREC AS INT
  DECLARE @RESULT_TABLE TABLE
  (
 RES_ID INT,
 RES_PRODUCTID INT,
 RES_PRODUCTNUMBER NVARCHAR(25)
  )
  
  INSERT INTO @RESULT_TABLE 
  SELECT TOP 10
  ROW_NUMBER() OVER (ORDER BY PRODUCTID) AS ROWID,
  PRODUCTID,
  PRODUCTNUMBER
  FROM
  [Production].Product  
   SET @TOTALREC = (SELECT COUNT(*) FROM @RESULT_TABLE)  
   SET @COUNTER = 1
   WHILE @COUNTER <= @TOTALREC
   BEGIN
   SELECT RES_PRODUCTID, RES_PRODUCTNUMBER FROM @RESULT_TABLE WHERE RES_ID = @COUNTER
   SET @COUNTER = @COUNTER + 1
   END

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

SQL

Jobs Autos Real estate Videos Power by Google