Skip to main content

PL/SQL Cursors

 In PL/SQL, cursors are pointers to the context area in memory where SQL query results are stored.

They are used to fetch and manipulate query results row-by-row. Implicit cursors are automatically

created for single-row queries and DML statements, while explicit cursors must be explicitly declared

and controlled for multi-row queries.

Explicit cursors provide fine control over the fetching process,

allowing the use of attributes like %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN.

Cursors can also be parameterized to accept arguments dynamically.



 

IMPLICIT CURSOR

Implicit cursors are automatically created by Oracle when a SQL statement is executed.

They are used for single-row queries and do not need to be explicitly declared or managed by the programmer.

Implicit cursors are suitable for simple queries that return a single result.

DECLARE

   v_emp_name employees.first_name%TYPE;

BEGIN

   SELECT first_name INTO v_emp_name FROM employees WHERE employee_id = 100;

   DBMS_OUTPUT.PUT_LINE('Employee name: ' || v_emp_name);

END;

In PL/SQL, an implicit cursor is automatically created and managed by the Oracle engine when you execute a SQL query that returns a single row.

·  DECLARE: This keyword starts the declaration section where variables (v_emp_name in this case) are defined.

  • v_emp_name employees.first_name%TYPE;: Declares v_emp_name as a variable of type employees.first_name%TYPE. This uses the %TYPE attribute to associate v_emp_name with the data type of the first_name column in the employees table.

·  BEGIN: Marks the beginning of the executable section of the PL/SQL block, where actual logic and statements are written.

·  SELECT first_name INTO v_emp_name FROM employees WHERE employee_id = 100;: This is the SQL query that uses an implicit cursor.

  • SELECT first_name INTO v_emp_name: Executes a query to retrieve the first_name of an employee whose employee_id is 100 from the employees table. The INTO clause assigns the retrieved value to the variable v_emp_name.

·  DBMS_OUTPUT.PUT_LINE('Employee name: ' || v_emp_name);: Outputs the value of v_emp_name to the console using the DBMS_OUTPUT.PUT_LINE procedure. This displays the employee's first name based on the query result.

·  END;: Marks the end of the PL/SQL block.

 


EXPLICIT CURSOR

Explicit cursors are defined and managed by the programmer.

They provide more control and flexibility, especially for queries that return multiple rows.

Explicit cursors have to be explicitly declared, opened, fetched, and closed.

Declaration: Define the cursor's structure and query in the declaration section.

Opening: Open the cursor to establish the result set.

Fetching: Retrieve rows one by one from the result set.

Closing: Close the cursor when done

DECLARE

   CURSOR emp_cursor IS

      SELECT employee_id, first_name, last_name FROM employees;

   v_emp_id employees.employee_id%TYPE;

   v_emp_fname employees.first_name%TYPE;

   v_emp_lname employees.last_name%TYPE;

BEGIN

   OPEN emp_cursor;

   LOOP

      FETCH emp_cursor INTO v_emp_id, v_emp_fname, v_emp_lname;

      EXIT WHEN emp_cursor%NOTFOUND;

      DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_emp_id || ', Name: ' || v_emp_fname || ' ' || v_emp_lname);

   END LOOP;

   CLOSE emp_cursor;

END;

This PL/SQL code snippet demonstrates the use of a cursor to fetch and process multiple rows from the employees table:

1.     DECLARE: This keyword starts the declaration section where variables (emp_cursor, v_emp_id, v_emp_fname, v_emp_lname in this case) are defined.

o   CURSOR emp_cursor IS: Defines a cursor named emp_cursor that retrieves data from the employees table.

o   SELECT employee_id, first_name, last_name FROM employees;: Specifies the SQL query that the cursor will execute to fetch data.

o   v_emp_id employees.employee_id%TYPE;: Declares v_emp_id as a variable of type employees.employee_id%TYPE, which matches the data type of the employee_id column in the employees table.

o   v_emp_fname employees.first_name%TYPE;: Declares v_emp_fname as a variable of type employees.first_name%TYPE, matching the data type of the first_name column.

o   v_emp_lname employees.last_name%TYPE;: Declares v_emp_lname as a variable of type employees.last_name%TYPE, matching the data type of the last_name column.

2.     BEGIN: Marks the beginning of the executable section of the PL/SQL block, where actual logic and statements are written.

3.     OPEN emp_cursor: Opens the cursor emp_cursor to start fetching rows from the result set defined by the query.

4.     LOOP: Initiates a loop to fetch each row returned by the cursor until all rows have been processed.

o   FETCH emp_cursor INTO v_emp_id, v_emp_fname, v_emp_lname: Retrieves the next row from emp_cursor and assigns the values of employee_id, first_name, and last_name to v_emp_id, v_emp_fname, and v_emp_lname respectively.

o   EXIT WHEN emp_cursor%NOTFOUND: Checks if there are no more rows to fetch (%NOTFOUND attribute of the cursor). If no more rows are found, the loop is exited.

o   DBMS_OUTPUT.PUT_LINE: Outputs the fetched data (Employee ID, Name) to the console using DBMS_OUTPUT.PUT_LINE.

5.     END LOOP: Marks the end of the loop structure.

6.     CLOSE emp_cursor: Closes the cursor emp_cursor to release associated resources and complete the operation.

7.     END;: Marks the end of the PL/SQL block.

 


Explicit Cursor: Parameterized Cursors

Explicit cursors can also accept parameters, allowing you to pass values into the query when opening the cursor.

DECLARE

    CURSOR emp_cursor (dept_id NUMBER) IS

        SELECT employee_id, first_name, last_name FROM employees WHERE department_id = dept_id;

   

    v_employee_id employees.employee_id%TYPE;

    v_first_name employees.first_name%TYPE;

    v_last_name employees.last_name%TYPE;

BEGIN

    OPEN emp_cursor(10);

   

    LOOP

        FETCH emp_cursor INTO v_employee_id, v_first_name, v_last_name;

       

        EXIT WHEN emp_cursor%NOTFOUND;

       

        DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_employee_id || ', Name: ' || v_first_name || ' ' || v_last_name);

    END LOOP;

   

    CLOSE emp_cursor;

END;

This PL/SQL code snippet demonstrates the use of a cursor with parameters (a parameterized cursor) to fetch and process rows based on a specific department ID:

1.     DECLARE: This keyword starts the declaration section where variables (emp_cursor, v_employee_id, v_first_name, v_last_name in this case) are defined.

o   CURSOR emp_cursor (dept_id NUMBER) IS: Defines a cursor named emp_cursor that accepts a parameter dept_id of type NUMBER.

o   SELECT employee_id, first_name, last_name FROM employees WHERE department_id = dept_id;: Specifies the SQL query that the cursor will execute. It retrieves employee_id, first_name, and last_name for employees belonging to a specific department identified by dept_id.

o   v_employee_id employees.employee_id%TYPE;: Declares v_employee_id as a variable of type employees.employee_id%TYPE, matching the data type of the employee_id column in the employees table.

o   v_first_name employees.first_name%TYPE;: Declares v_first_name as a variable of type employees.first_name%TYPE, matching the data type of the first_name column.

o   v_last_name employees.last_name%TYPE;: Declares v_last_name as a variable of type employees.last_name%TYPE, matching the data type of the last_name column.

2.     BEGIN: Marks the beginning of the executable section of the PL/SQL block, where actual logic and statements are written.

3.     OPEN emp_cursor(10): Opens the cursor emp_cursor with the parameter value 10. This executes the cursor query for employees belonging to the department with department_id = 10.

4.     LOOP: Initiates a loop to fetch each row returned by the cursor until all rows have been processed.

o   FETCH emp_cursor INTO v_employee_id, v_first_name, v_last_name: Retrieves the next row from emp_cursor and assigns the values of employee_id, first_name, and last_name to v_employee_id, v_first_name, and v_last_name respectively.

o   EXIT WHEN emp_cursor%NOTFOUND: Checks if there are no more rows to fetch (%NOTFOUND attribute of the cursor). If no more rows are found, the loop is exited.

o   DBMS_OUTPUT.PUT_LINE: Outputs the fetched data (Employee ID, Name) to the console using DBMS_OUTPUT.PUT_LINE.

5.     END LOOP: Marks the end of the loop structure.

6.     CLOSE emp_cursor: Closes the cursor emp_cursor to release associated resources and complete the operation.

7.     END;: Marks the end of the PL/SQL block.

 


Explicit Cursor: Cursor FOR Loops

A cursor FOR loop simplifies cursor handling by implicitly declaring, opening, fetching, and closing the cursor.

BEGIN

FOR emp_record IN (SELECT employee_id, first_name, last_name FROM employees WHERE department_id = 10)

 

LOOP DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_record.employee_id || ', Name: ' || emp_record.first_name || ' ' || emp_record.last_name);

END LOOP; END;

This PL/SQL code snippet demonstrates the use of a FOR loop to iterate over a result set obtained from a SQL query:

·  FOR emp_record IN (SELECT ...): This line starts a FOR loop where emp_record is the loop index variable. The loop iterates over each row returned by the SQL query (SELECT employee_id, first_name, last_name FROM employees WHERE department_id = 10).

  • SELECT employee_id, first_name, last_name FROM employees WHERE department_id = 10: This SQL query retrieves employee_id, first_name, and last_name from the employees table where department_id = 10.
  • emp_record is a record type implicitly declared to match the structure of the columns selected in the query (employee_id, first_name, last_name).

·  LOOP: Begins the loop structure where each iteration processes one row fetched by the cursor implicitly created by the FOR loop.

·  DBMS_OUTPUT.PUT_LINE: Outputs each employee's ID and full name (employee_id, first_name, last_name) to the console using DBMS_OUTPUT.PUT_LINE.

  • emp_record.employee_id, emp_record.first_name, emp_record.last_name: These refer to the specific fields (employee_id, first_name, last_name) of the current row being processed in the loop.

·  END LOOP: Marks the end of the loop structure.

·  END;: Marks the end of the PL/SQL block.

 

 

 

 

 

 

 

 

 

 

 


Comments

Popular posts from this blog

Performance Optimization

Performance optimization in SQL is crucial for ensuring that your database queries run efficiently, especially as the size and complexity of your data grow. Here are several strategies and techniques to optimize SQL performance: Indexing Create Indexes : Primary Key and Unique Indexes : These are automatically indexed. Ensure that your tables have primary keys and unique constraints where applicable. Foreign Keys : Index foreign key columns to speed up join operations. Composite Indexes : Use these when queries filter on multiple columns. The order of columns in the index should match the order in the query conditions. Avoid Over-Indexing:  Too many indexes can slow down write operations (INSERT, UPDATE, DELETE). Only index columns that are frequently used in WHERE clauses, JOIN conditions, and as sorting keys. Query Optimization Use SELECT Statements Efficiently : SELECT Only Necessary Columns : Avoid using SELECT * ; specify only ...

DAX UPPER Function

The DAX UPPER function in Power BI is used to convert all characters in a text string to uppercase. This function is useful for standardizing text data, ensuring consistency in text values, and performing case-insensitive comparisons. Syntax: UPPER(<text>) <text>: The text string that you want to convert to uppercase. Purpose: The UPPER function helps ensure that text data is consistently formatted in uppercase. This can be essential for tasks like data cleaning, preparing text for comparisons, and ensuring uniformity in text-based fields. E xample: Suppose you have a table named "Customers" with a column "Name" that contains names in mixed case. You want to create a new column that shows all names in uppercase. UppercaseName = UPPER(Customers[Name]) Example Scenario: Assume you have the following "Customers" table: You can use the UPPER function as follows: Using the UPPER function, you can convert all names to uppercase: UppercaseName = ...

TechUplift: Elevating Your Expertise in Every Click

  Unlock the potential of data with SQL Fundamental: Master querying, managing, and manipulating databases effortlessly. Empower your database mastery with PL/SQL: Unleash the full potential of Oracle databases through advanced programming and optimization. Unlock the Potential of Programming for Innovation and Efficiency.  Transform raw data into actionable insights effortlessly. Empower Your Data Strategy with Power Dataware: Unleash the Potential of Data for Strategic Insights and Decision Making.