Created On:  01 July 2010

Problem:

I need to limit the number of rows that will be returned in a cursor fetch to a specified number when using SQL Server.  How is this done?

Resolution:

The SELECT TOP (n) construct can be used to limit the number of rows returned to (n) number of rows.

Example: Only 2 rows will be returned until the fetch results in a SQLCODE = 100 no more records.

EXEC SQL                                                 
 DECLARE CSR3 CURSOR FOR SELECT TOP (2)                  
        "A"."CustomerID"                                 
       ,"A"."CompanyName"                                
       ,"A"."ContactName"                                
   FROM "Customers" A                                    
END-EXEC                                                 

EXEC SQL  OPEN CSR3 END-EXEC                             
PERFORM UNTIL SQLCODE < 0 OR SQLCODE = 100              
  EXEC SQL                                               
  FETCH CSR3 INTO                                        
      :Customers-CustomerID                              
     ,:Customers-CompanyName                             
     ,:Customers-ContactName:Customers-ContactName-NULL  
  END-EXEC                                                
  IF SQLCODE  = 0                                        
     continue                                             
   END-IF                                                
END-PERFORM                                              
EXEC SQL  CLOSE CSR3 END-EXEC                            
                                                         
                                                         
Incident #2462249