在Oracle中执行Dynamic Sql查询

时间:2014-03-06 06:29:12

标签: sql oracle stored-procedures plsql

我有一个SELECT查询,其中我将有一个动态WHERE条件。问题是当我尝试将WHERE条件PARAMETER与SQL查询连接时,它不允许我保存PROCEDURE

例如:

CREATE PROCEDURE usp_MySearchQuery
(
  QTYPE IN INT,
  OUT_CUR OUT SYS_REFCURSOR
)
IS
DYN_QUERY VARCHAR2;
BEGIN
    IF QTYPE=1 THEN
       DYN_QUERY :=' BETWEEN 1 AND 2';
    ELSE
       DYN_QUERY :='=10';    
    END IF;

    OPEN OUT_CUR FOR
         SELECT * FROM MYTABLE WHERE TYPE=QTYPE AND ID || DYN_QUERY;
END;

这是我的程序的样子。 我尝试了EXECUTE IMMEDIETE,但在其文档本身中,它写的不适用于多行查询。

MSSQL中,我们有EXEC(不确定)命令,可以execute发送给命令的文本。以同样的方式,我们有任何可以在Oracle

中运行动态查询的命令
UPDATE: Answer

我试过这样。

  OPEN OUT_CUR FOR
        ' SELECT * FROM MYTABLE WHERE TYPE=:QTYPE AND ID ' || DYN_QUERY
          USING QTYPE;

并且有效

1 个答案:

答案 0 :(得分:3)

动态字符串必须包含在“单引号”

OPEN OUT_CUR FOR
     'SELECT * FROM MYTABLE WHERE ID '|| DYN_QUERY;
如果您使用EXECUTE IMMEDIATE,则

BULK COLLECT允许多行结果 示例:

DECLARE
  TYPE myarray IS TABLE OF VARCHAR2(100);
  v_array myarray;
BEGIN
  EXECUTE IMMEDIATE 'select ''x'' from dual union all select ''y'' from dual'
    BULK COLLECT INTO v_array;

  --Or you could use the alternative quoting mechanism to avoid doubling quotation marks.
  --EXECUTE IMMEDIATE q'[select 'x' from dual union all select 'y' from dual]'
  --  BULK COLLECT INTO v_array;

  FOR i IN 1..v_array.count
  LOOP
    DBMS_OUTPUT.PUT_LINE(v_array(i));
  END LOOP;
END;

EXECUTE IMMEDIATE使用绑定变量;

String := 'SELECT * FROM EMP WHERE name = :name AND age = :age AND :name <> ''Mahesh''';

EXECUTE IMMEDIATE String USING 'Mahi',21,'Mahi';
<OR>
EXECUTE IMMEDIATE String USING proc_variable1,proc_variable2,proc_variable1;