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

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.

Python Topics

Learning Python can be an exciting and rewarding journey, especially given its versatility and widespread use in various fields like web development, data science, automation, and more. Here's a structured guide to help you learn Python effectively, covering essential topics from beginner to advanced levels. Beginner Level Introduction to Python Installation and setup Python syntax and interactive shell Writing and running your first Python script Basic Concepts Variables and data types (integers, floats, strings, booleans) Basic arithmetic operations String operation Comments and documentation Control Structures Conditional statements ( if ,  elif ,  else ) Loops ( for ,  while ) Data Structures Lists Tuples Dictionaries Sets Functions Defining and calling functions Function arguments and return values Lambda functions Built-in functions Modules and Packages Importing modules Standard library overview (e.g.,  math ,  datetime ,  random ) Installing and using external packages

DAX Functions

These are just some of the many DAX functions available in Power BI. Each  function serves a specific purpose and can be used to perform a wide range of calculations and transformations on your data. Aggregation Functions: SUM : Calculates the sum of values. AVERAGE : Calculates the arithmetic mean of values. MIN : Returns the smallest value in a column. MAX : Returns the largest value in a column. COUNT : Counts the number of rows in a table or column. COUNTA : Counts the number of non-blank values in a column. DISTINCTCOUNT : Counts the number of unique values in a column. Logical Functions: IF : Returns one value if a condition is true and another value if it's false. AND : Returns TRUE if all the conditions are true, otherwise FALSE. OR : Returns TRUE if any of the conditions are true, otherwise FALSE. NOT : Returns the opposite of a logical value. Text Functions: CONCATENATE : Concatenates strings together. LEFT : Returns the leftmost characters from a text string. RIGHT : Ret