使用带有绑定的立即执行的存储过程
Stored Procedure using Execute Immediate with binding
我有一个可用的存储过程并且想要 improve/simplify 它。
CREATE OR REPLACE PROCEDURE DOCSADM.DRILL_COUNTV5 ( IN_TABLE IN VARCHAR2, IN_TYPE IN VARCHAR2, OUT_COUNT OUT NUMBER) AS
BEGIN
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || IN_TABLE
|| ' WHERE TYPEVALUE = ''' || IN_TYPE || ''' '
into OUT_COUNT;
END DRILL_COUNTV5;
/
理想情况下,我想让它更容易扩展。我想重写 execute immediate 行,如
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || IN_TABLE
|| ' WHERE TYPEVALUE = '':IN_TYPE'' '
into OUT_COUNT;
当我使用这种方法时,我得到 0 作为我的 return 值。
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM :IN_TABLE WHERE TYPEVALUE = ''' || IN_TYPE
|| ''' ' into OUT_COUNT;
这个给了我"ORA-00903: invalid table name"。
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || IN_TABLE
|| ' WHERE TYPEVALUE = '':1'' '
into OUT_COUNT using IN_TYPE;
给我 "ORA-01006: bind variable does not exist".
如果 table 绑定没有发生,我不太介意,因为这样的绑定会更少,但我真的希望能够进行 where 绑定而不使用串联。
document from Oracle 给了我几种方法,但是当我尝试它们时,它们都不起作用。
在你的程序中使用 USING 子句怎么样:
CREATE TABLE ttt(
typevalue varchar2(10)
);
INSERT INTO ttt VALUES('123');
DECLARE
IN_TABLE varchar2(10) := 'ttt';
typval varchar2(10) := '123';
OUT_COUNT number;
BEGIN
EXECUTE IMMEDIATE
'SELECT COUNT(*) FROM ' || IN_TABLE || ' WHERE TYPEVALUE = :p '
INTO OUT_COUNT USING IN typval;
DBMS_OUTPUT.PUT_LINE( OUT_COUNT );
END;
/
==============================
dbms_output:
1
演示:https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=1fb7e29017e3c5f4309ed25bbeddf7f6
我有一个可用的存储过程并且想要 improve/simplify 它。
CREATE OR REPLACE PROCEDURE DOCSADM.DRILL_COUNTV5 ( IN_TABLE IN VARCHAR2, IN_TYPE IN VARCHAR2, OUT_COUNT OUT NUMBER) AS
BEGIN
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || IN_TABLE
|| ' WHERE TYPEVALUE = ''' || IN_TYPE || ''' '
into OUT_COUNT;
END DRILL_COUNTV5;
/
理想情况下,我想让它更容易扩展。我想重写 execute immediate 行,如
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || IN_TABLE
|| ' WHERE TYPEVALUE = '':IN_TYPE'' '
into OUT_COUNT;
当我使用这种方法时,我得到 0 作为我的 return 值。
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM :IN_TABLE WHERE TYPEVALUE = ''' || IN_TYPE
|| ''' ' into OUT_COUNT;
这个给了我"ORA-00903: invalid table name"。
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || IN_TABLE
|| ' WHERE TYPEVALUE = '':1'' '
into OUT_COUNT using IN_TYPE;
给我 "ORA-01006: bind variable does not exist".
如果 table 绑定没有发生,我不太介意,因为这样的绑定会更少,但我真的希望能够进行 where 绑定而不使用串联。
document from Oracle 给了我几种方法,但是当我尝试它们时,它们都不起作用。
在你的程序中使用 USING 子句怎么样:
CREATE TABLE ttt(
typevalue varchar2(10)
);
INSERT INTO ttt VALUES('123');
DECLARE
IN_TABLE varchar2(10) := 'ttt';
typval varchar2(10) := '123';
OUT_COUNT number;
BEGIN
EXECUTE IMMEDIATE
'SELECT COUNT(*) FROM ' || IN_TABLE || ' WHERE TYPEVALUE = :p '
INTO OUT_COUNT USING IN typval;
DBMS_OUTPUT.PUT_LINE( OUT_COUNT );
END;
/
==============================
dbms_output:
1
演示:https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=1fb7e29017e3c5f4309ed25bbeddf7f6