该特性与C语言的类似。从Oracle 9.2.0.6开始被引入,9.2.0.6默认关闭该特性,可以通过一个参数打开。10gR1默认是打开,可以关闭。10gR2或以上默认打开,不可以关闭。常用于以下场景:
Conditional Compilation有三种元素:
Selective Directives:
$IF $THEN $ELSEIF $ELSE $END
Inquiry Directives: 用$$引用
NLS_Length_Semantics
PLSQL_Optimize_Level: 0-3. 11gR2, 默认2. 1: PL/SQL 优化器基本不改变代码。0: 不改变代码,同时将代码中BINARY_INTEGER和PLS_INTEGER替换为效率稍低的类型。10g+Oracle使用这个级别会有性能损失。
PLSQL_Code_Type
PLSQL_Debug:deprecated.
PLSQL_Warnings: 11gR2默认'DISABLE:ALL', 表示忽略所有Warning信息。
alter session set plsql_warnings='ENABLE:SEVERE'
将severe信息作为Warning。
alter session set plsql_warnings='ENABLE:INFORMATIONAL'
alter system set plsql_warnings='enable:performance', 'enable:severe';
PLSQL_CCFLAGS 。码农可以用PLSQL_CCFLAGS自定义一些控制参数,如:ALTER SESSION SET PLSQL_CCFLAGS = 'debug:TRUE'
PLSQL_UNIT: 当前代码段
PLSQL_LINE:代码行
Error Directives: $ERROR,指令预编译器报错。
两个辅助PL/SQL包
DBMS_DB_VERSION
DBMS_PREPROCESSOR:用户可以看到预编译完毕的代码
例子1: 使用$error编译时报错
begin
$if true $then
$error 'Error: Go to ' || $$plsql_unit || ' at line ' || $$plsql_line
$end
end;
例子2:$error 结合plsql_ccflags
ALTER SESSION SET PLSQL_CCFLAGS = 'current_user_type:0'
CREATE OR REPLACE PACKAGE user_types
IS
administrator CONSTANT PLS_INTEGER := 1;
enduser CONSTANT PLS_INTEGER := 2;
END user_types;
CREATE OR REPLACE PROCEDURE show_info
IS
BEGIN
$IF $$current_user_type = user_types.administrator
$THEN
DBMS_OUTPUT.PUT_LINE ('Administrator!');
$elsif $$current_user_type = user_types.enduser
$THEN
DBMS_OUTPUT.PUT_LINE ('End user!');
$ELSE
$ERROR 'Current user type of ' || $$current_user_type || ' is not known.' $END
$END
end show_info;
show errors;
11/6 PLS-00179: $ERROR: Current user type of 0 is not known.
例子3: Oracle数据库版本相关
CREATE OR REPLACE PROCEDURE
crunch_numbers
IS
n $IF DBMS_DB_VERSION.VER_LE_9_2
$THEN NUMBER;
$ELSE BINARY_FLOAT;
$END
BEGIN
$IF DBMS_DB_VERSION.VER_LE_9_2
$THEN n := 1.0;
$ELSE n := 1.0f;
$END
DBMS_OUTPUT.put_line ( n );
END crunch_numbers;
例子4: DEV环境,打开Tracing
alter session set plsql_ccflags = 'tracing:true';
create or replace procedure p1
as
begin
$if $$tracing = true $then
dbms_output.put_line('xx');
$end
null;
end;
本文部分例子借鉴了Oracle Magazine
http://www.oracle.com/technetwork/issue-archive/2006/06-jul/o46plsql-096385.html
DBMS_PREPROCESSOR.print_post_processed_source:
set serveroutput on;
exec DBMS_PREPROCESSOR.PRINT_POST_PROCESSED_SOURCE('PROCEDURE',NULL, UPPER('crunch_numbers'));