Cursor does duplicate records

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • antonopn
    New Member
    • Mar 2008
    • 42

    Cursor does duplicate records

    Hello there,

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

    Code:
    DECLARE CUR CURSOR FOR SELECT * FROM TABLE_READ
    OPEN CUR 
    WHILE @@FETCH_STATUS=0
    BEGIN
    FETCH NEXT FROM CUR INTO 
    @local_var1
    @local_var2
    ...
    
    INSERT INTO TABLE_WRITE VALUES (@local_var1, @local_var2...)
    END
    CLOSE CUR
    DEALLOCATE CUR
    GO
    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
    Recognized Expert Top Contributor
    • Jan 2008
    • 1134

    #2
    [code=sql]
    DECLARE CUR CURSOR FOR SELECT * FROM TABLE_READ
    OPEN CUR
    FETCH NEXT FROM CUR INTO
    @local_var1
    @local_var2

    WHILE @@FETCH_STATUS= 0
    BEGIN
    INSERT INTO TABLE_WRITE VALUES (@local_var1, @local_var2...)
    FETCH NEXT FROM CUR INTO
    @local_var1
    @local_var2
    END
    CLOSE CUR
    DEALLOCATE CUR
    GO
    [/code]

    May I ask, why are you using a cursor for this?

    [code=sql]
    INSERT INTO TABLE_WRITE
    SELECT * FROM TABLE_READ
    [/code]
    would run far faster than the cursor
    cursors are recommended as a last resort only because they are slow and inefficient

    Comment

    • antonopn
      New Member
      • Mar 2008
      • 42

      #3
      Thanks for your answer!

      Lets suppose I need cursor! My problem is not why should I use cursor but why this "mistake" occurs!

      Comment

      • Delerna
        Recognized Expert Top Contributor
        • Jan 2008
        • 1134

        #4
        my apologies
        I gave you the answer

        Comment

        • antonopn
          New Member
          • Mar 2008
          • 42

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

          It works fine!!!

          Comment

          Working...