Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

FETCH FIRST 1

Status
Not open for further replies.

wawanz

Programmer
Aug 29, 2002
62
ID
Hi guys...I have table Y with 700 records, with, say, two columns: column A, column B. I want to update column A with data from a column in table X but, table X only has 50 records. So what I'm trying to do is, update the first 50 rows of column A with data from table X, then loop back to the first row of table X to update the next 50 rows of table Y, and so on. Here's what I did:

Code:
DECLARE @szSuppId varchar(50), @counter int

DECLARE supp_cursor SCROLL CURSOR FOR
SELECT szSuppId FROM X
ORDER BY szSuppId

OPEN supp_cursor

FETCH NEXT FROM supp_cursor
INTO @szSuppId

SET @counter = 1

WHILE @@FETCH_STATUS = 0
BEGIN

   UPDATE [Y] SET szSuppId=@szSuppId
   WHERE CAST(szSuppId AS int)=@counter 
   
   SET @counter=@counter + 1

   FETCH NEXT FROM supp_cursor
   INTO @szSuppId
	
   IF NOT @@FETCH_STATUS = 0    ---return to the first row 
   BEGIN
     FETCH FIRST FROM supp_cursor
     INTO @szSuppId
   END

END

CLOSE supp_cursor
DEALLOCATE supp_cursor
GO

My problem is: I accomplished what I wanted, but the query seemed to go into an indefinite loop. After I stopped the query, and checked table Y, it did exactly what I intended. But it doesn't feel right because of the indefinite loop. Any idea on what I did wrong? Note: I use SQL Server 2005 Enterprise Edition.

Thanks guys.
 
Of course it loops forever - there is no BREAK condition that will terminate loop when there are no more rows in Y to update.

Btw. I'm pretty sure this can be done without cursor.

------
[small]select stuff(stuff(replicate('<P> <B> ', 14), 109, 0, '<.'), 112, 0, '/')[/small]
[banghead]
 
Oh I thought the @@FETCH_STATUS = 0 means something like the EOF in VB. Will try using the BREAK condition. Thank you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top