PLSQL:动态表记录保持器

时间:2012-11-14 17:53:09

标签: dynamic plsql cursor

如果我想从表中获取记录(表名是输入动态的),如何定义记录持有者或如何从这个定义的表中获取数据? p_table_name%rowtype 将无法编译,因为p_table_name是参数,而不是表名。

PROCEDURE do_scan(p_table_name IN VARCHAR2
    ,p_min_num IN NUMBER
    ,p_time_range IN NUMBER
    ,p_problem_desc OUT
    ,p_result_code OUT) 
IS
    TYPE ObjCurTyp  IS REF CURSOR;
    v_obj_cursor    ObjCurTyp;
    v_obj_record     ???????(p_table_name%rowtype)
BEGIN
    v_stmt_str := 'Select * from :t where date_started > TRUNC(SYSDATE-3)';
    OPEN v_obj_cursor FOR v_stmt_str USING p_table_name;

    LOOP
        FETCH v_obj_cursor INTO v_obj_record;
            EXIT WHEN v_obj_cursor %NOTFOUND;

    END LOOP;

END do_scan;

1 个答案:

答案 0 :(得分:1)

您可以将该代码作为动态PL / SQL块放在EXECUTE IMMEDIATE语句中。

PROCEDURE do_scan
(
    p_table_name    IN VARCHAR2
    p_min_num       IN NUMBER
    p_time_range    IN NUMBER
    p_problem_desc  OUT
    p_result_code   OUT
) 
IS
BEGIN
    EXECUTE IMMEDIATE
        'DECLARE '                                           ||
        '    TYPE ObjCurTyp  IS REF CURSOR; '                ||
        '    v_obj_cursor    ObjCurTyp; '                    ||
        '    v_obj_record   ' || p_table_name || '%rowtype; '||
        'BEGIN '                                             ||
        '    v_stmt_str := ''Select * from :t where '        || 
        '        date_started > TRUNC(SYSDATE-3)''; '        ||
        '    OPEN v_obj_cursor '                             ||
        '        FOR v_stmt_str USING '                      || 
                 p_table_name || '; '                        ||
        '    LOOP '                                          ||
        '        FETCH v_obj_cursor INTO v_obj_record; '     ||
        '           EXIT WHEN v_obj_cursor %NOTFOUND; '      ||
        '    END LOOP; '                                     ||
        'END;';
END do_scan;

此致

Dariyoosh