Results 1 to 5 of 5

Thread: Refactor code with cursor - different results

  1. #1
    Join Date
    Oct 2005
    Location
    Ireland
    Posts
    92

    Refactor code with cursor - different results

    I am refactoring a stored proc, the intention being to replace a cursor with more efficient code. the outline is as follows.

    DECLARE @Table abc
    INSERT INTO @Table ... SELECT From ...
    UPDATE @Table SET field1 = 'a', field2 = 'b'

    -- Code with cursor here: ----------------
    DECLARE CURSOR x FOR SELECT IDField, field3, field4 FROM @Table
    OPEN x
    WHILE ...
    SELECT @Var1 = fielda, @Var2 = fieldb from TableValuedfunctionx(@field3, @field4)

    UPDATE @Table SET field5 = @Var1, field6 = @Var2 where IDField = @IDField
    END
    ------------------------------------------
    -- Replacement code here: ----------------
    UPDATE @Table
    SET field5 = (SELECT fielda from TableValuedfunctionx(field3, field4),
    SET field6 = (SELECT fieldb from TableValuedfunctionx(field3, field4)
    ------------------------------------------



    When I SELECT * from @Table at the end of this code, some of the values in field5 and field6 are null where they had values when I was using a cursor.
    Note: the function TableValuedfunctionx is fairly complex, declaring multiple table variables and joining these to various other tables to produce the table it returns.
    Is the problem here the fact I'm calling this function multiple times in the one UPDATE statement or is it something else?
    Last edited by bobbo; 06-24-2009 at 05:31 AM.

  2. #2
    Join Date
    Nov 2002
    Location
    New Jersey, USA
    Posts
    3,932

  3. #3
    Join Date
    Oct 2005
    Location
    Ireland
    Posts
    92
    The original method returned no null values. the new method returns nulls for some rows but not for others.

  4. #4
    Join Date
    Nov 2002
    Location
    New Jersey, USA
    Posts
    3,932
    Can run

    SELECT fielda from TableValuedfunctionx(field3, field4)

    for the rows where you are getting NULLs to see if this is returning correct value.

  5. #5
    Join Date
    Oct 2005
    Location
    Ireland
    Posts
    92
    I ran this

    SELECT fielda from TableValuedfunctionx(field3, field4)

    and no data was returned. At this point I began to suspect that my code was good and it was the existing code that was suspect.

    I talked to the developer that wrote the code originally (not too long ago) and he is making the recommended change.

    Thanks for your help.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •