SET @FromDate = GETDATE() - 30
SET @ToDate = GETDATE()
DECLARE LateCountCursor CURSOR
SELECT DISTINCT IDRess, COUNT(Late) AS LateCount
WHERE (DateInvolved BETWEEN GETDATE() - 30 AND GETDATE()) AND (Late = 1)
GROUP BY IDRess
ORDER BY IDRess
-- Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE @@FETCH_STATUS = 0
FETCH NEXT FROM LateCountCursor
INTO @IDRess, @LateCounter
IF @LateCounter >= 1
DECLARE @late int, @dept int, @sup int, @poste int, @patron int
SELECT @late = (SELECT ID_NOTICE FROM TBL_NOTICE_TYPE WHERE NoticeName = 'Late')
DECLARE RessCursor CURSOR
SELECT IDDepartement, IDContremaitre, IDPoste, IDPatron FROM TBL_RESSOURCES WHERE IDInterne = @IDRess
IF @@FETCH_STATUS = 0
FETCH NEXT FROM RessCursor
INTO @dept, @sup, @poste, @patron
the query you have posted won't even write two records. It won't actually do anything.
Your 'FETCH NEXT FROM LateCountCursor ' line comes after your 'WHILE @@FETCH_STATUS = 0' line, so the @@FetchStatus will be -1 (try print @@Fetch_Status to see). Because it is -1, the compiler will not even enter the while loop, therefore none of the code will be performed. Your 'FETCH NEXT FROM LateCountCursor ' line should come before the 'WHILE @@FETCH_STATUS = 0' line to ensure that the code in the while loop is actually implemented.
As far as I know there is no tool that will allow you to step through TSQL code. SQL Server creates a query plan for the code before it is actually exectuted, and the sequence of events in that query plan does not neccesarily match the sequence of code.
Actually, @@FETCH_STATUS could be 0 depending on what
the status of the last FETCH was before gdo's code block was
started. Since @@FETCH_STATUS is global to all cursors in a
connection, it might be valid upon entry to tis code block.
I agree the condition checking of @@FETCH_STATUS needs to
be changed as you mentioned. Gdo might get two inserts performed
one call, then zero the next with the current setup.