question

AAC avatar image
AAC asked

SQL Cursor updates same value for all rows

I am trying to use a cursor to update a value in the PAYG column. The cursor should select just one value for PAYG based on the date that is immediately greater than the date from the main table it is comparing with. But it seems to update all the rows with the same maximum value from the table. I have tried the 'SELECT TOP1*' statement with hard coded values and this seems to do as required. But i am not sure why it is grabbing the same value. The query is as below:-


DECLARE


@REF char(8),

@Start_Date date

,@PAYG char(10)

IF OBJECT_ID('TE_Cursor') IS NOT NULL -- Drop cursor first in case it exists already

DROP PROC TE_Cursor

-- Get all PHIST Details

DECLARE TE_Cursor CURSOR FOR

SELECT REF, Start_Date, PAYG

FROM Test_Emp_Details ORDER BY REF, D580_Start_Date ASC

OPEN TE_Cursor

FETCH NEXT FROM TE_Cursor

INTO

@REF,

@Start_Date

,@PAYG

WHILE ( @@FETCH_STATUS = 0 )

BEGIN

UPDATE [Test_Emp_Details]

SET PAYG = ( SELECT TOP 1 PAYG FROM PGHIST_PAYG

WHERE REF = @REF

AND EFFECT_DATE >= @Start_Date

ORDER BY EFFECT_DATE DESC

)

WHERE REF = @REF

FETCH NEXT FROM TE_Cursor INTO @REF, @Start_Date, @PAYG

END

CLOSE TE_Cursor

DEALLOCATE TE_Cursor


END


--Test_Emp_DEtails

1697115346908.png


--Test_PGHIST_PAYG

1697115470200.png

Appreciate any help on this. Thanks

cursor
1697115346908.png (6.7 KiB)
1697115470200.png (9.0 KiB)
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
anthony.green avatar image
anthony.green answered

Is your code right?

The PAYG table is detailed as "PGHIST_PAYG" and not "Test_PGHIST_PAYG"

You actually pulling the data from the right table?
Does PGHIST_PAYG actually have any data in it which matches the conditions?

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.