动态SQL | PL / SQL

时间:2014-01-12 18:08:35

标签: sql oracle dynamic-sql

我遇到了动态SQL的麻烦,我希望能够显示department_id:

CREATE OR REPLACE PROCEDURE pro_two_tables
    (p_input VARCHAR2) IS
     v_department_id employees.department_id%TYPE;

BEGIN
    EXECUTE IMMEDIATE
       'SELECT department_id
    /* MYSTERY FOR ME */
           FROM ' || p_input || '
              WHERE manager_id = 205';
DBMS_OUTPUT.PUT_LINE('You selected ID from the table' || ' ' || p_input || ' ' || 'ID   is' ||' ' || v_department_id);

EXCEPTION
   WHEN NO_DATA_FOUND THEN
      DBMS_OUTPUT.PUT_LINE('No data found');
   WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE(' I petty the fool who wrote this');
END; 

我似乎无法理解如何在此过程中使用“INTO”子句。 我正在阅读这个问题并做一些“测试”,尽管我认为这是很有帮助的 如果有人能向我解释这一点。

2 个答案:

答案 0 :(得分:1)

INTO落后于执行立即执行,如

declare
    foo number;
    bar number;

begin
    execute immediate 'select 1,2 from dual' into foo, bar;
    dbms_output.put_line(foo ||','||bar);
end;
/

打印:

1,2

请注意,如果您发现自己使用的是动态SQL,那么通常最好检查一下您的设计。

答案 1 :(得分:0)

CREATE OR REPLACE PROCEDURE pro_two_tables (i_table_name VARCHAR2)
IS
   v_record_id     NUMBER;
   v_record_name   VARCHAR2 (500) := 'Name Record'; -- Insert your Name Value
   sql_stmt        VARCHAR2 (500);
BEGIN
   sql_stmt :=
      'SELECT id
           FROM ' || i_table_name || ' WHERE name = :1';

   EXECUTE IMMEDIATE sql_stmt INTO   v_record_id USING v_record_name;

   DBMS_OUTPUT.PUT_LINE(   'You selected ID from the table'
                        || ' '
                        || i_table_name
                        || ' '
                        || 'ID   is'
                        || ' '
                        || v_record_id);
EXCEPTION
   WHEN NO_DATA_FOUND
   THEN
      DBMS_OUTPUT.PUT_LINE ('No data found');
   WHEN OTHERS
   THEN
      DBMS_OUTPUT.PUT_LINE (' I petty the fool who wrote this');
END;

使用EXECUTE IMMEDIATE,您可以使用:

  1. INTO for Return Single Value o BULK COLLECT INTO for Multiple Value。
  2. 在您的查询语句中使用替换绑定变量,并将其放在sql中,格式为:[name_field]