counting rows before processing with a cursor tsql
If you are able to declare your cursor as STATIC
then you can use the built in function @@Cursor_Rows
Cursor Options (Static/ReadOnly/Dynamic)
@@Cursor_Rows
if exists(
SELECT
tblHSOutcomes.strOutcomeName,
tblHSData.fkHSTest
FROM
tblHSData
INNER JOIN tblHSOutcomes ON tblHSData.fkOutcome = tblHSOutcomes.uidOutcome
INNER JOIN tblHSTests ON tblHSData.fkHSTest = tblHSTests.uidTest
WHERE
tblHSData.fkEpisode = @uidHSEpisodes
)
...
Here is a example of how to use @@Cursor_Rows
DECLARE TestCursor CURSOR STATIC FOR
SELECT <snip>
OPEN TestCursor
IF @@Cursor_Rows > 0 BEGIN
FETCH NEXT FROM TestCursor INTO @compid, @logid, @category
WHILE @@FETCH_STATUS = 0 BEGIN
<snip>
END
CLOSE TestCursor
DEALLOCATE TestCursor
Please note that you need to declare the cursor STATIC
(or KEYSET
)