如何在EXECUTE IMMEDIATE中使用动态where子句

时间:2018-08-16 06:07:41

标签: sql oracle plsql

我有一张表,其中包含插入,选择,where子句,动态where子句,group by子句。

使用过程我需要执行insert into语句,还需要使用动态where子句。

我尝试了以下方法,但是它给了我一个错误的表达式。

create or replace PROCEDURE dynamicWhereClause(Datee IN DATE,processId IN NUMBER)
IS 

 processName VARCHAR2(100);
 tablePrefix CONFIG_DETAILS.SOURCE_TABLE%Type;
 sourceTableType CONFIG_DETAILS.SOURCE_TABLE_TYPE%Type;
 insertClause CONFIG_DETAILS.INSERT_CLAUSE%Type;
 selectClause CONFIG_DETAILS.SELECT_CLAUSE%Type;
 whereClause CONFIG_DETAILS.WHERE_CLAUSE%Type;
 onUpdateClause CONFIG_DETAILS.ON_UPDATE_CLAUSE%Type;
 groupByClause CONFIG_DETAILS.GROUP_BY_CLAUSE%Type;
 orderByClause CONFIG_DETAILS.ORDER_BY_CLAUSE%Type;
 isDynamicWhereClause CONFIG_DETAILS.IS_DYNAMIC_WHERE_CLAUSE%Type;
 tableName VARCHAR2(50);
 Process_Date DATE;
 processQuery VARCHAR2(6000 BYTE);


 CURSOR Process_Report IS 
    select NAME,SOURCE_TABLE,SOURCE_TABLE_TYPE,INSERT_CLAUSE,SELECT_CLAUSE,WHERE_CLAUSE,ON_UPDATE_CLAUSE,GROUP_BY_CLAUSE,ORDER_BY_CLAUSE,IS_DYNAMIC_WHERE_CLAUSE FROM 
    CONFIG_DETAILS where ID=processId;

BEGIN

    OPEN Process_Report;
    LOOP

        FETCH Process_Report INTO processName,tablePrefix,sourceTableType,insertClause,selectClause,whereClause,onUpdateClause,groupByClause,orderByClause,isDynamicWhereClause;
            EXIT when Process_Report%NOTFOUND;

        tableName := getSourceTableName(tablePrefix,sourceTableType,processDate);
        Process_Date := processDate;

        processQuery := insertClause || selectClause ||' from ' || tableName ||' ' ||
        nvl(whereClause,'') ||''||nvl(groupByClause,'') ||''||nvl(orderByClause,'') ||''||nvl(onUpdateClause,'');

        dbms_output.put_line(processQuery);

        IF isDynamicWhereClause = 'Y' 
        THEN
            dbms_output.put_line(processQuery);
            EXECUTE IMMEDIATE processQuery USING Process_Date;  

        ELSE

            EXECUTE IMMEDIATE  processQuery;

        END IF;

    END LOOP;
    CLOSE Process_Report;

END;

执行proc时,出现以下错误。

Error report -
ORA-00936: missing expression
ORA-06512: at "Mytest.dynamicWhereClause", line 44
ORA-06512: at line 1
00936. 00000 -  "missing expression"

请进一步帮助我

谢谢

1 个答案:

答案 0 :(得分:0)

您的问题不是100%清楚。您说DATEE为空之后,是否要在date之后分配变量?以下是如何对变量使用立即执行的示例。请注意,绑定变量:i在打印中的显示方式。

set serveroutput on size 1000 
/
declare t number(4) :=10;
txt varchar2(100);
begin
txt :='INSERT INTO TAB (ID) values (:i)';
dbms_output.put_line(t || ' ' || txt);
execute immediate txt using T;
end;
/

PL/SQL procedure successfully completed

10 INSERT INTO TAB (ID) values (:i)