OPEN
Example
Section titled “Example”DECLARE @CustomerCursor CURSORDECLARE @CustomerID int, @CustomerName nvarchar(50)
SET @CustomerCursor = CURSOR FORSELECT CustomerID, CustomerName FROM Customers
OPEN @CustomerCursorFETCH NEXT FROM @CustomerCursor INTO @CustomerID, @CustomerName
WHILE @@FETCH_STATUS = 0BEGIN PRINT CAST(@CustomerID AS varchar(11)) + ' - ' + @CustomerName FETCH NEXT FROM @CustomerCursor INTO @CustomerID, @CustomerNameEND
CLOSE @CustomerCursorDEALLOCATE @CustomerCursorOutput
Section titled “Output”1 - John Doe2 - Jane Smith3 - Robert Williams4 - Linda JohnsonExplanation
Section titled “Explanation”The OPEN statement in SQL is used to open a cursor, which is a database object to retrieve data from a result set one row at a time. The example packages the cursor declaration, opening, fetching data, and closing into a single transaction block. Each customer from the Customers table is printed out one at a time by their ID and name.
Example
Section titled “Example”DECLARE CURSOR employee_cursor IS SELECT first_name, last_name FROM employees WHERE department_id = 10; employee_rec employee_cursor%ROWTYPE;BEGIN OPEN employee_cursor; FETCH employee_cursor INTO employee_rec; CLOSE employee_cursor;END;/Output
Section titled “Output”PL/SQL procedure successfully completed.Explanation
Section titled “Explanation”In the provided SQL script, an explicit cursor employee_cursor is declared, which holds the result set from the query that extracts the first_name and last_name from the ‘employees’ table for those employees who belong to department number 10.
The OPEN command initializes the cursor for fetching and makes it point to the first row in the result set. FETCH pull a row from the result set into a record, and finally, CLOSE shuts down the cursor. The output indicates the successful execution of the PL/SQL block.