# Database Discussions > Microsoft SQL Server 2005 >  Refactor code with cursor - different results

## bobbo

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?

----------


## skhanal

Are some values null or all values?

----------


## bobbo

The original method returned no null values. the new method returns nulls for some rows but not for others.

----------


## skhanal

Can run 

SELECT fielda from TableValuedfunctionx(field3, field4)

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

----------


## bobbo

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.

----------

