i have declare a cursor in one procedure and make a loop inside it. but when i execute procedure cursor occur only first time what happen to this i want it occur everytime when procedure is executed.
DECLARE SUP_CUR CURSOR SCROLL DYNAMIC FOR SELECT * FROM @saleSup
DECLARE @SUP_TEMP AS INT
OPEN SUP_CUR
WHILE @@FETCH_STATUS =0
BEGIN
FETCH NEXT FROM SUP_CUR INTO @SUP_TEMP
SELECT COUNT (DISTINCT saleRepId),userId FROM @tabletemp WHERE userId = @SUP_TEMP GROUP BY userId
END
CLOSE SUP_CUR;
DEALLOCATE SUP_CUR;
Put FETCH NEXT to end of loop and add first FETCH
DECLARE SUP_CUR CURSOR SCROLL DYNAMIC FOR SELECT * FROM @saleSup
DECLARE @SUP_TEMP AS INT
OPEN SUP_CUR
FETCH NEXT FROM SUP_CUR INTO @SUP_TEMP
WHILE @@FETCH_STATUS =0
BEGIN
SELECT COUNT (DISTINCT saleRepId),userId FROM @tabletemp WHERE userId = @SUP_TEMP GROUP BY userId
FETCH NEXT FROM SUP_CUR INTO @SUP_TEMP
END
CLOSE SUP_CUR;
DEALLOCATE SUP_CUR;
Change your cursor
like this. You need to add fetch before the start of while loop to fetch the first row
and at the end of while loop
add FETCH NEXT
to fetch the next row
DECLARE @SUP_TEMP AS INT
DECLARE SUP_CUR CURSOR SCROLL DYNAMIC FOR
SELECT *
FROM @saleSup
OPEN SUP_CUR
-- Perform the first fetch.
FETCH NEXT FROM SUP_CUR INTO @SUP_TEMP
-- Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT Count (DISTINCT saleRepId),
userId
FROM @tabletemp
WHERE userId = @SUP_TEMP
GROUP BY userId
-- This is executed as long as the previous fetch succeeds.
FETCH NEXT FROM SUP_CUR INTO @SUP_TEMP
END
CLOSE SUP_CUR;
DEALLOCATE SUP_CUR;
now i know what problem with it. i just put
FETCH NEXT FROM SUP_CUR INTO @SUP_TEMP
before start loop and move FETCH NEXT to below select statement in loop and that work properly
I don't think you need to use a cursor (they are bad practice anyway), try:
SELECT COUNT (DISTINCT saleRepId),userId
FROM @tabletemp
GROUP BY userId
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.