我有一个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;
并且有效
答案 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;