【问题标题】:Oracle SQL - SELECT with Variable arguments stored procedureOracle SQL - 带有变量参数的 SELECT 存储过程
【发布时间】:2017-07-06 12:45:55
【问题描述】:

我正在为 variable argument 存储过程而苦苦挣扎,该存储过程必须使用在其 WHERE 子句中传递给它的每个参数对表执行 SELECT。

基本上我有 N 个帐号 作为参数,我想返回一个表格,其中包含为每个帐号选择三个字段的结果。

这是我到目前为止所做的:

function sp_get_minutes_expiration_default(retval IN OUT char, gc IN OUT GenericCursor,
        p_account_num IN CLIENT_ACCOUNTS.ACCOUNT_NUM%TYPE) return number
        is
    r_cod integer := 0;
    begin
        open gc for select account_num, concept_def, minutes_expiration_def from CLIENT_ACCOUNTS
            where p_account_num = account_num;  -- MAYBE A FOR LOOP HERE?
        return r_cod;
    exception

        -- EXCEPTION HANDLING

    end sp_get_minutes_expiration_default;

我的蛮力解决方案可能是遍历帐号列表,选择并可能执行 UNION 或附加到结果表?

【问题讨论】:

    标签: sql oracle parameter-passing


    【解决方案1】:

    如果您将输入参数转换为表格,则可以将其加入 CLIENT_ACCOUNTS

    select account_num, concept_def, minutes_expiration_def
    from CLIENT_ACCOUNTS ca, table(p_account_num) a
    where a.account_num = ca.account_num
    

    但我建议您将输出选择到另一个集合中,该集合是函数(或过程)的输出。我会敦促你不要使用参考游标。

    附录 1

    一个更完整的例子如下:

    create or replace type id_type_array as table of number;
    /
    
    declare
       ti id_type_array := id_type_array();
       n number;
    begin
       ti.extend();
       ti(1) := 42;
       select column_value into n from table(ti) where rownum = 1;
    end;
    /
    

    在您的代码中,您需要使用框架的 API 来:

    1. 创建集合的实例(类型为 id_type_array)
    2. 用数字列表填充集合
    3. 执行匿名 PL/SQL 块,绑定在集合中

    但是您应该立即看到,您不必将查询放入匿名 PL/SQL 块中来执行它(尽管 许多 有经验的 Oracle 开发人员提倡这样做)。只要绑定正确的参数,就可以像执行任何其他查询一样执行查询:

    select account_num, concept_def, minutes_expiration_def
    from CLIENT_ACCOUNTS ca, table(:p_account_num) a
    where a.column_value = ca.account_num
    

    【讨论】:

    • @jeff5times7 在这个简短的例子中,p_account_num 应该是什么类型,一个 SQL LIST?我一直在阅读 TABLE() 函数,但我不太明白它需要什么参数。你能再扩大一点吗?
    • 请参阅附录 1。
    猜你喜欢
    • 2012-01-12
    • 1970-01-01
    • 2010-11-02
    • 2013-11-17
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    相关资源
    最近更新 更多