PLSQL
PLSQL
Maithili Paranjape
Objectives
A cursor can be viewed as a pointer to one row in a set of rows. The cursor can only
reference one row at a time, but can move to other rows of the result set as needed.
To use cursors in SQL procedures, you need to do the following:
Declare a cursor that defines a result set.
Open the cursor to establish the result set.
Fetch the data into local variables as needed from the cursor, one row at a time.
Close the cursor when done
To work with cursors you must use the following SQL statements:
DECLARE CURSOR
OPEN
FETCH
CLOSE
use myproject;
DECLARE
@emp_name VARCHAR(MAX),
@emp_salary DECIMAL;
Example Ename,
Salary
FROM
Employee;
Steps:
1. Declare two variables to hold OPEN cursor_emp;
the data in attributes, and a
cursor to hold the result of a FETCH NEXT FROM cursor_emp INTO
query @emp_name,
2. Open the cursor @emp_salary;
3. Fetch each row from the
cursor WHILE @@FETCH_STATUS = 0
4. Close the cursor BEGIN
5. Deallocate the cursor PRINT @emp_name + CAST(@emp_salary AS
varchar);
FETCH NEXT FROM cursor_emp INTO
@emp_name,
@emp_salary;