简体   繁体   中英

SQL Server: cursor only returns records first time when running in Management Studio

I'm hoping someone can help with this! I'm trying to write a stored procedure that uses a cursor. When I test this in Management Studio, the sproc only returns records the first time it's run. If I copy/past to another query window, it again returns records only the first time. When run from C#, the sproc works as expected.

The query below demonstrates the problem. Thanks in advance!

-------------------------------------------------------------------
-- Query to reproduce problem with using cursor - management studio
-------------------------------------------------------------------
--
Declare     crsrTest Cursor For 
Select      TABLE_NAME 
From        INFORMATION_SCHEMA.TABLES; 

Declare     @TableName  varchar(128);
Open        crsrTest;  

-- 
-- This will only return records the *first* time when running in MS. 
-- Every time after that, I get the 'No records' message. 
-- 
if @@FETCH_STATUS <> 0 
    Print 'No records';             
while   @@FETCH_STATUS = 0 begin 
    Fetch   Next 
    From    crsrTest
    Into    @TableName;  
    Print   @TableName;
end;

Close       crsrTest; 
Deallocate  crsrTest; 

You are missing a FETCH NEXT between the OPEN and IF @@FETCH_STATUS <> 0 :

DECLARE crsrTest CURSOR FOR
     SELECT TABLE_NAME 
     FROM INFORMATION_SCHEMA.TABLES; 

DECLARE @TableName VARCHAR(128);

OPEN crsrTest;  

FETCH NEXT FROM crsrTest INTO @TableName;
PRINT @TableName;

-- This will always return records
IF @@FETCH_STATUS <> 0 
   PRINT 'No records';             

WHILE @@FETCH_STATUS = 0 
BEGIN
    FETCH NEXT FROM crsrTest INTO @TableName;
    PRINT @TableName;
END;

CLOSE crsrTest; 
DEALLOCATE crsrTest;

Stay away from cursors if you can (you seem to be new at them, that's why I'm telling). If you're an ORACLE guy, this is not as fast as iterations in PL/SQL.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM