Connecting Tech Pros Worldwide Help | Site Map

Cursor does duplicate records

antonopn's Avatar
Member
 
Join Date: Mar 2008
Posts: 41
#1: Jul 25 '08
Hello there,

this is my problem. I have a table in sql server. lets say it table_read.
I use a cursor like this.

Expand|Select|Wrap|Line Numbers
  1. DECLARE CUR CURSOR FOR SELECT * FROM TABLE_READ
  2. OPEN CUR 
  3. WHILE @@FETCH_STATUS=0
  4. BEGIN
  5. FETCH NEXT FROM CUR INTO 
  6. @local_var1
  7. @local_var2
  8. ...
  9.  
  10. INSERT INTO TABLE_WRITE VALUES (@local_var1, @local_var2...)
  11. END
  12. CLOSE CUR
  13. DEALLOCATE CUR
  14. GO
  15.  
But my problem is that the last row of table_read is inserted twice in table_write!

Any solutions? Should I fix the cursor or try to remove duplicate records from table_write?

Thank you!
Delerna's Avatar
Expert
 
Join Date: Jan 2008
Location: Sydney
Posts: 783
#2: Jul 25 '08

re: Cursor does duplicate records


Expand|Select|Wrap|Line Numbers
  1. DECLARE CUR CURSOR FOR SELECT * FROM TABLE_READ
  2. OPEN CUR 
  3. FETCH NEXT FROM CUR INTO 
  4. @local_var1
  5. @local_var2
  6.  
  7. WHILE @@FETCH_STATUS=0
  8. BEGIN
  9.    INSERT INTO TABLE_WRITE VALUES (@local_var1, @local_var2...)
  10.    FETCH NEXT FROM CUR INTO 
  11.    @local_var1
  12.    @local_var2
  13. END
  14. CLOSE CUR
  15. DEALLOCATE CUR
  16. GO
  17.  
May I ask, why are you using a cursor for this?

Expand|Select|Wrap|Line Numbers
  1. INSERT INTO TABLE_WRITE 
  2. SELECT * FROM TABLE_READ
  3.  
would run far faster than the cursor
cursors are recommended as a last resort only because they are slow and inefficient
antonopn's Avatar
Member
 
Join Date: Mar 2008
Posts: 41
#3: Jul 27 '08

re: Cursor does duplicate records


Thanks for your answer!

Lets suppose I need cursor! My problem is not why should I use cursor but why this "mistake" occurs!
Delerna's Avatar
Expert
 
Join Date: Jan 2008
Location: Sydney
Posts: 783
#4: Jul 28 '08

re: Cursor does duplicate records


my apologies
I gave you the answer
antonopn's Avatar
Member
 
Join Date: Mar 2008
Posts: 41
#5: Jul 28 '08

re: Cursor does duplicate records


MY APOLOGIES not yours :)
Thanks for the answer one more time!!!

It works fine!!!
Reply