如何在pl / sql中对动态列和动态排序方向进行排序

时间:2014-05-30 05:36:37

标签: oracle plsql

如何编写具有动态列和动态排序方向的pl / sql,例如: -

select * from table order by "dynamic column" "dynamic sort order";

2 个答案:

答案 0 :(得分:1)

您基本上需要将sql命令构造为字符串,然后动态执行它。

DECLARE
  TYPE EmpCurTyp  IS REF CURSOR;
  v_emp_cursor    EmpCurTyp;
  emp_record      employees%ROWTYPE;
  v_stmt_str      VARCHAR2(200);
  v_order         VARCHAR2(30);
  v_e_job         employees.job%TYPE;
BEGIN
  -- Dynamic SQL statement with placeholder:
  v_order := 'emplid DESC';
  v_stmt_str := 'SELECT * FROM employees WHERE job_id = :j ORDER BY ' || v_order;

  -- Open cursor & specify bind argument in USING clause:
  OPEN v_emp_cursor FOR v_stmt_str USING 'MANAGER';

  -- Fetch rows from result set one at a time:
  LOOP
    FETCH v_emp_cursor INTO emp_record;
    EXIT WHEN v_emp_cursor%NOTFOUND;
  END LOOP;

  -- Close cursor:
  CLOSE v_emp_cursor;
END;
/

答案 1 :(得分:0)

您可以使用dynamic SQL& REF CURSORS动态构建查询

DECLARE
    TYPE cur_typ IS ref CURSOR;
    emp_rec_cursor CUR_TYP;
    v_query_str    VARCHAR2(2000);
    v_sort_order   VARCHAR2(10) := 'DESC';
    v_column       VARCHAR2(20) := 'NAME';
    v_empid        emp.empid%TYPE;
    v_name         emp.name%TYPE;
    v_salary       emp.salary%TYPE;
BEGIN
    query_str := 'SELECT empid, name, salary FROM emp order by '
                 || v_column   -- reassign v_column as needed
                 || '  '
                 || v_sort_order; -- reassign v_sort_order as needed

    OPEN emp_rec_cursor FOR query_str;

    LOOP
        FETCH emp_rec_cursor INTO v_empid, v_name, v_salary;

        EXIT WHEN emp_rec_cursor %NOTFOUND;
    -- process row here
    END LOOP;

    CLOSE emp_rec_cursor;
END;