Native Dynamic sql,立即执行

时间:2017-05-30 09:05:28

标签: oracle plsql

EXECUTE immediate 'SELECT COUNT(*) INTO var_total_rows FROM '||v_table_name   || ' where  ENQUIRY_NO = :enq_no' 
--INTO var_total_rows USING enq_no;

这是错误的关键字错误。我试图计算在传递每个表的查询号后获取的行数。输出中约有68个表

谢谢

1 个答案:

答案 0 :(得分:0)

您可以尝试这种方式:

DECLARE
   v_table_name     VARCHAR2 (20) := 'emp';
   enq_no           NUMBER := 5;
   var_total_rows   NUMBER;
BEGIN
   EXECUTE IMMEDIATE
      'SELECT COUNT(*) FROM  ' || v_table_name || ' where  EMPNO = :enq_no'
      INTO var_total_rows
      USING enq_no;

   DBMS_OUTPUT.put_line (var_total_rows);
END;

编辑: 这适合我。我刚刚将ENQUIRY_NO替换为EMPLOYEE_ID,因为我的架构没有该表。请确保为变量enq_no

指定值
declare
var_total_rows number;
enq_no number:=1;
BEGIN
   FOR c1 IN (SELECT DISTINCT table_name
                FROM user_tab_columns
               WHERE column_name = 'EMPLOYEE_ID' ) --'ENQUIRY_NO')
   LOOP
      DBMS_OUTPUT.PUT_LINE (' ');
      DBMS_OUTPUT.PUT_LINE ('Table = ' || c1.table_name);
      DBMS_OUTPUT.PUT_LINE ('=========================');

      EXECUTE IMMEDIATE
            'SELECT COUNT(*) FROM '
         || c1.table_name
         || ' where EMPLOYEE_ID = :enq_no'
         INTO var_total_rows
         USING enq_no;

      DBMS_OUTPUT.PUT_LINE ('total count:' || var_total_rows);
   END LOOP;
END;

输出:

Table = EMPLOYEE
=========================
total count:1
Table = BONUSES
=========================
total count:1
Table = BONUSESS
=========================
total count:0