I need to create and execute a query dynamically in a stored procedure.
I have two tables users and user_updates.
Employee table has emp_id, username, division, product, region, title etc.
Employee_updates has columns like emp_id, effective_date, column_name, new_value etc.
Basically this is what I want to do.
Get all employees having updates in user_udates table for a given effective date.
Loop over each employee.
Get all updates for each employeefor the given effective date. A employee may have one or more than one updates in employee_updates table.
Create a dynamic "UPDATE" query based on those updates like
update employee set col1 = new_val_1, col2 = new_val_2 where emp_id = ?
This is what I have done so far
create or replace
PROCEDURE SP_RUN_EMPLOYEE_UPDATES
(
IN_DATE IN DATE
)
IS
update_sql varchar2(225);
employee_id BI_EMPLOYEE_UPDATE.employee_id%TYPE;
CURSOR employees
IS SELECT distinct(employee_id)
FROM BI_EMPLOYEE_UPDATE
WHERE EFFECTIVE_DATE = to_date(IN_DATE,'dd-mm-yy')
AND EXECUTED = 'N' AND ACTIVITY_ID = '0'
;
CURSOR e_updates
IS SELECT *
FROM BI_EMPLOYEE_UPDATE
WHERE EFFECTIVE_DATE = to_date(IN_DATE,'dd-mm-yy')
AND EXECUTED = 'N'
AND ACTIVITY_ID = '0'
and employee_id = employee_id ;
BEGIN
OPEN employees;
LOOP
FETCH employees into employee_id;
EXIT WHEN employees%NOTFOUND;
FOR e_update in e_updates
update_sql := 'UPDATE BI_EMPLOYEE SET ';
LOOP
-- create dynam,ic update statment
UPDATE BI_EMPLOYEE_UPDATE
SET EXECUTED = 'Y'
WHERE EMPLOYEE_UPDATE_ID = e_update.EMPLOYEE_UPDATE_ID ;
END LOOP;
-- run dynamic sql
END LOOP;
CLOSE employees;
END;
PLease help.