Db2 Stored Procedure Example Explained | Generated by AI

Home 2025.08

Below is an example of an IBM Db2 stored procedure script, followed by a detailed explanation of its components and functionality.

Example Db2 Stored Procedure Script

-- Create a stored procedure to retrieve employee details by department
CREATE PROCEDURE GetEmployeeDetailsByDept (IN dept_id INTEGER)
    LANGUAGE SQL
    SPECIFIC GetEmpByDept
    DETERMINISTIC
    READS SQL DATA
BEGIN
    -- Declare variables
    DECLARE v_employee_id INTEGER;
    DECLARE v_first_name VARCHAR(50);
    DECLARE v_last_name VARCHAR(50);
    DECLARE v_salary DECIMAL(10,2);
    
    -- Declare cursor to fetch employee details
    DECLARE emp_cursor CURSOR WITH RETURN TO CALLER FOR
        SELECT employee_id, first_name, last_name, salary
        FROM employees
        WHERE department_id = dept_id
        ORDER BY last_name;
    
    -- Open the cursor
    OPEN emp_cursor;
    
    -- Optional: Error handling
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        SIGNAL SQLSTATE '75000'
        SET MESSAGE_TEXT = 'Error retrieving employee details';
    END;
END;

Explanation of the Stored Procedure

1. Purpose of the Stored Procedure

This stored procedure, GetEmployeeDetailsByDept, retrieves employee details (ID, first name, last name, and salary) from an employees table for a specified department ID. It uses a cursor to return a result set to the caller, which is useful for applications that need to process multiple rows.

2. Components of the Script

3. Variable Declarations

4. Cursor Definition

5. Cursor Operation

6. Error Handling

7. Assumptions

How to Call the Procedure

To execute this stored procedure in a Db2 environment, you can use:

CALL GetEmployeeDetailsByDept(10);

This retrieves all employees in department 10. The calling application (e.g., a SQL client or program) can then fetch the result set from the cursor.

Example Use Case

Suppose you have an employees table:

CREATE TABLE employees (
    employee_id INTEGER,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    salary DECIMAL(10,2),
    department_id INTEGER
);

If the table contains: | employee_id | first_name | last_name | salary | department_id | |————-|————|———–|———|—————| | 1 | John | Doe | 50000.00| 10 | | 2 | Jane | Smith | 60000.00| 10 | | 3 | Bob | Johnson | 55000.00| 20 |

Calling CALL GetEmployeeDetailsByDept(10) would return: | employee_id | first_name | last_name | salary | |————-|————|———–|———-| | 1 | John | Doe | 50000.00 | | 2 | Jane | Smith | 60000.00 |

Additional Notes

If you need a different type of Db2 stored procedure (e.g., one that updates data or uses loops), let me know, and I can provide another example!


Back Donate