在今天的工作中需要在过程中执行动态的SQL语句,用到了EXECUTE IMMEDIATE。示例为Sp_Rcpms_EITest.Prc过程,整个脚本如下:
--Name: Sp_Rcpms_EITest
--举例说明EXECUTE IMMEDIATE的简单使用
------------------
CREATE OR REPLACE PROCEDURE Sp_Rcpms_EITest(
v_result OUT NUMBER)
AS
l_month VARCHAR2(7);
l_month1 VARCHAR2(6);
l_datetime VARCHAR2(19);
l_tablename VARCHAR2(30);
l_sql VARCHAR2(512);
l_result INTEGER;
BEGIN
SELECT TO_CHAR(ADD_MONTHS(SYSDATE, -1),'YYYY-MM') mon INTO l_month FROM dual;
SELECT TO_CHAR(ADD_MONTHS(SYSDATE, -1),'YYYYMM') mon INTO l_month1 FROM dual;
SELECT TO_CHAR(SYSDATE,'YYYY-MM-DD') INTO l_datetime FROM dual;
l_datetime := l_datetime||' 00:00:00';
--动态变名
l_tablename := 'rcpms_cardinfo'||l_month1;
l_sql := 'INSERT INTO RCPMS_REPORTMONTHAREA(STATE,AREAID,MONEY,CARDCOUNT,TOTALMONEY,COUNTTIME,cardtype) '||
'SELECT ''0'',AREAID,MONEY,COUNT(*),SUM(RESIDUALMONEY),l_month,TYPE '||
'FROM '||l_tablename||
' WHERE fdatetime >= l_datetime AND state = ''2'' AND money <> residualmoney AND residualmoney <> 0 '||
'GROUP BY AREAID,MONEY,TYPE';
EXECUTE IMMEDIATE(l_sql);
v_result := 0;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
v_result := 9;
ROLLBACK;
l_result := SQLCODE;
INSERT INTO TAB_MOVE_ERRLOG VALUES(TO_CHAR(SYSDATE,'YYYY-MM-DD HH24:MI:SS'), l_result);
COMMIT;
END Sp_Rcpms_EITest;
/
------------------
现把自己一些要点总结如下:
1. 据说使用EXECUTE IMMEDIATE能提高一些性能;
2. 如果需要在字符串中包含字符,用''来代表一个单引号;
3. EXECUTE IMMEDIATE中的EXECUTE不能简写为exec,测试环境为oracle 8i;
4. EXECUTE IMMEDIATE中执行DML语句不会自动提交,需要显示COMMIT;执行DDL语句提交所有之前改变的语句。
5. 使用绑定变量,如:
l_tablename := 'back_cardinfo_'||l_firstmon;
EXECUTE IMMEDIATE 'SELECT count(*) FROM '||l_tablename||' WHERE areaid = '||l_AreaID||' AND (state = '||l_state8||' or state = '||l_state9||') AND money = '||l_Money INTO l_count;
IF l_count > 0 THEN
l_hisyearcount := l_count;
ELSE
l_hisyearcount := 0;
END IF;
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/9896745/viewspace-988776/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/9896745/viewspace-988776/