oracle中条件的动态选择
嗨,我想做的是将搜索标准作为我的函数的参数,并根据输入参数在表格中搜索。。例如:如果所有参数都为NULL,则函数将返回表中的evey字段,如果参数不为NULL,则该参数将作为搜索条件。我可以做一个If声明,但它太长了,假设我有一个更大的桌子,这将是非常痛苦的,我有什么办法可以完成这项任务?谢谢 我的代码:oracle中条件的动态选择,oracle,plsql,Oracle,Plsql,嗨,我想做的是将搜索标准作为我的函数的参数,并根据输入参数在表格中搜索。。例如:如果所有参数都为NULL,则函数将返回表中的evey字段,如果参数不为NULL,则该参数将作为搜索条件。我可以做一个If声明,但它太长了,假设我有一个更大的桌子,这将是非常痛苦的,我有什么办法可以完成这项任务?谢谢 我的代码: create or replace type ordersinf as object(orderDate DATE, orderName VARCHAR2(20), orderPrice NU
create or replace type ordersinf as object(orderDate DATE, orderName VARCHAR2(20), orderPrice NUMBER)
create or replace type orders_tab IS TABLE OF ordersinf
我的代码是:
create or replace function execImmFunc(orderDate DATE, orderName in
VARCHAR2, orderPrice in NUMBER) return orders_tab is
Result orders_tab := orders_tab();
begin
SELECT ordersinf(orderDate => orders_Orderdate, orderName => orderName,orderPrice => orders_price)
BULK COLLECT INTO RESULT
FROM orders_table
WHERE orders_Orderdate >= orderDate OR orders_name = orderName OR orders_price = orderPrice ;
return(Result);
end execImmFunc;
大概是这样的:
CREATE OR REPLACE FUNCTION execImmFunc(
orderDate IN DATE,
orderName IN VARCHAR2,
orderPrice IN NUMBER
) RETURN orders_tab
IS
Result orders_tab;
BEGIN
SELECT ordersinf(
orderDate => orders_OrderDate,
orderName => orders_Name,
orderPrice => orders_price
)
BULK COLLECT INTO Result
FROM orders_table
WHERE ( orderDate IS NULL OR orders_OrderDate >= orderDate )
AND ( orderName IS NULL OR orders_name = orderName )
AND ( orderPrice IS NULL OR orders_price = orderPrice );
RETURN Result;
END execImmFunc;
这就是你的意思吗
WHERE (orderDate is null OR orders_Orderdate >= orderDate) AND (orderName is null OR orders_name = orderName) AND (orderPrice is null OR orders_price = orderPrice );
如果参数orderDate为null-子句将通过并被有效忽略
嘿,我没有工作空间,但下面是一个非常简单的片段
可根据提供的输入用于动态sql生成。
希望这有帮助
您是否试图设置使参数在resultset中返回或在where子句中使用?看起来不像是这样,而是希望返回所有列,并仅当它们不为null时才在where中使用参数 如果是这样,为什么不只是一个经典的nvl设置
SELECT ordersinf(orderDate => orders_Orderdate
,orderName => orderName
,orderPrice => orders_price)
BULK COLLECT INTO RESULT
FROM orders_table
WHERE orders_Orderdate >= nvl(orderDate, orders_Orderdate)
OR orders_name = nvl(orderName, orders_name)
OR orders_price = nvl(orderPrice, orders_price);
我认为这些ORs应该是,而且您可能希望发送的所有条件都是真实的,但这纯粹是一个设计/需求问题。或者您可以编写
orders\u name=COALESCE(orderName,orders\u name)
@WernfriedDomscheit,在这种情况下,当OP测试每个条件是否相等时,它将起作用(即,=
,=
或根据所问问题,这种方法也可以在函数中实现。虽然这种方法可行,但效率低下,因为它没有使用绑定变量,因此优化器必须单独查看每个查询(因为它们都有不同的硬编码参数).Bind变量仍然可能-。尽管不需要双重调用。(正确的)重建查询始终是最佳解决方案。@MaheswaranRavisankar:没错。双重调用可以避免,而Bind变量无论如何都是可能的:)
SELECT ordersinf(orderDate => orders_Orderdate
,orderName => orderName
,orderPrice => orders_price)
BULK COLLECT INTO RESULT
FROM orders_table
WHERE orders_Orderdate >= nvl(orderDate, orders_Orderdate)
OR orders_name = nvl(orderName, orders_name)
OR orders_price = nvl(orderPrice, orders_price);