存储函数中的oracle游标,使用参数

时间:2017-06-20 13:15:06

标签: oracle plsql oracle11g oracle12c

在存储函数中,我需要使用一些子子选择进行“动态”查询:

CURSOR c_dyn
AS
    SELECT 'CREATE SYNONYM '
        || username_parameter_from_function
        ||'.'
        ||o.object_name
        || ' FOR '
        || o.OWNER
        ||'.'
        || o.object_name
        ||';' AS OUT_SQL
    FROM SYS.DBA_OBJECTS o
    WHERE o.object_type IN ( 'TABLE', 'VIEW', 'SEQUENCE')
    AND o.OWNER         IN
        (
            SELECT DISTINCT x.OWNER
            FROM SYS.dba_tab_privs x
            WHERE x.GRANTEE IN
                (
                    SELECT DISTINCT p.granted_role
                    FROM SYS.dba_role_privs p
                    WHERE p.GRANTEE=username_parameter_from_function
                )
        AND NOT OWNER LIKE 'SYS%'
        );

这里我们有一些“sub”选择和一个来自函数的参数。这不适用于某个功能。任何想法如何“重新塑造”这个?或mabye改变功能以获得相同的结果?或者有没有办法让它按原样工作......?

谢谢! 中号

1 个答案:

答案 0 :(得分:0)

我建议使用cursors with parameters 一个例子:

CURSOR c_dyn(username_param varchar2)
AS
    SELECT 'CREATE SYNONYM '
        || username_param
        || '.'
        || o.object_name
        || ' FOR '
        || o.OWNER
        ||'.'
        || o.object_name
        ||';' AS OUT_SQL
    FROM SYS.DBA_OBJECTS o
    WHERE o.object_type IN ( 'TABLE', 'VIEW', 'SEQUENCE')
    AND o.OWNER         IN
        (
            SELECT DISTINCT x.OWNER
            FROM SYS.dba_tab_privs x
            WHERE x.GRANTEE IN
                (
                    SELECT DISTINCT p.granted_role
                    FROM SYS.dba_role_privs p
                    WHERE p.GRANTEE = username_param
                )
        AND NOT OWNER LIKE 'SYS%'
        );