In this example cursor statement, the SQL database just prints the customers. If there is no row to fetch, the cursor FOR LOOP closes the cursor. An infinite loop must be terminated and stopped from your database administrator. Here’s an easy example of a cursor that loops through MyTable and gets an ID and a string from each row: / Set up variables to hold the current record were working on / DECLARE CurrentID INT, CurrentString VARCHAR (100) DECLARE cursorresults CURSOR FOR SELECT MyID, MyString FROM dbo.MyTable OPEN. In each loop iteration, the cursor FOR LOOP statement fetches a row from the result set into its loop index. The cursor FOR LOOP implicitly creates its loop index as a record variable with the row type in which the cursor returns and then opens the cursor. Cursors are user-defined iterative variables that allow us to access the query results or the results of the stored procedure. Similarly, the cursor FOR LOOP executes the body of the loop once for each row returned by the query associated with the cursor.Ī nice feature of the cursor FOR LOOP statement is that it allows you to fetch every row from a cursor without manually managing the execution cycle i.e., OPEN, FETCH, and CLOSE. The numeric FOR LOOP executes the body of a loop once for every integer value in a specified range. The cursor FOR LOOP statement is an elegant extension of the numeric FOR LOOP statement.
Introduction to PL/SQL cursor FOR LOOP statement
Sql cursor how to#
Summary: in this tutorial, you will learn how to use the PL/SQL cursor FOR LOOP statement to fetch and process every record from a cursor.