构建光标查询动态性质?

时间:2014-12-26 08:53:41

标签: oracle plsql cursor

我在 PL / SQL函数中使用了以下光标,即getEmployeeInfo

CURSOR employeeDepartment IS
        SELECT *
        FROM Employee
        LEFT OUTER JOIN Department ON Department.empID = Employee.ID
        WHERE Employee.STATE = 'Washington'
        ORDER BY Employee.JoiningDate desc;

我需要修改getEmployeeInfo 功能,将 employeeId作为输入参数并附加到游标employeeDepartment 如果employeeId>0

我是PL / SQL编程的新手。看起来我需要朝着 REF-CURSOR 的方向前进,但我无法完全弥补?

如果 Employee.id>那么光标查询应该在下面。 0 否则应与上述相同

CURSOR employeeDepartment IS
        SELECT *
        FROM Employee
        LEFT OUTER JOIN Department ON Department.empID = Employee.ID
        WHERE Employee.STATE = 'Washington'
        and Employee.id= 100
        ORDER BY Employee.JoiningDate desc;

更新: - @APC解决方案有效。通过使用该解决方案,如果我想要传递empId的数组而不是单个Id我在下面尝试过

首先使用create type p_employee_arr as table of number

创建数组类型
CURSOR employeeDepartment  (p_employee_arr IN num_array) IS
    SELECT *
    FROM Employee
    LEFT OUTER JOIN Department ON Department.empID = Employee.ID
    WHERE Employee.STATE = 'Washington'
    and (Employee.id in  (SELECT column_value  FROM TABLE( p_employee_arr )) or p_employee_arr is null)
    ORDER BY Employee.JoiningDate desc;

但是如果我在数组中提供一个元素

,它仍会返回完整的结果集

2 个答案:

答案 0 :(得分:1)

我认为您需要带有如下参数

的光标
CURSOR employeeDepartment (employee_id_in IN number)
IS
        SELECT *
        FROM Employee
        LEFT OUTER JOIN Department ON Department.empID = Employee.ID
        WHERE Employee.STATE = 'Washington'
        and 
        (case 
               when (employee_id_in > 0) and (Employee.id= employee_id_in)  then 1
        else 0
        end) = 1 
        ORDER BY Employee.JoiningDate desc;

因此您可以像

一样打开光标
open employeeDepartment(100)

有关详细信息,请参阅http://www.techonthenet.com/oracle/cursors/declare.php

答案 1 :(得分:1)

您的问题有点含糊不清但我认为您希望在传递员工ID时限制结果集,否则您需要状态的所有记录。

CURSOR employeeDepartment  (p_employee_id in number) IS
    SELECT *
    FROM Employee
    LEFT OUTER JOIN Department ON Department.empID = Employee.ID
    WHERE Employee.STATE = 'Washington'
    and ( p_employee_id = 0 or Employee.id= p_employee_id )
    ORDER BY Employee.JoiningDate desc;