前段时间,应工作要求,要在orcale数据库中写两个根据传入表名创建备份表,并且复制表结构和相关数据。
写的过程中,需要在' '中内嵌' ',当时在网上看了很多博客,都是一样的建议用转义,样例基本上都一样,感觉十分麻烦。
无疑中看到一个博客上用ASCII码进行拼接,顿时觉得见到了曙光,且拼接出来的sql很清晰。
样例:
create or replace procedure proc_migration_data(tf_table_name in varchar2) is
tf_date varchar2(16);
tf_date_before varchar2(16);
tf_data_nd varchar2(16);
tf_table_black_name VARCHAR2(64);
tf_table_sql varchar2(1024);
tf_table_sql_del varchar2(1024);
begin
select to_char(sysdate,'yyyymm') into tf_date from dual;
select to_char(sysdate -1,'yyyy-mm-dd') into tf_date_before from dual;
select to_char(sysdate,'yyyy-mm-dd') into tf_data_nd from dual;
tf_table_black_name := tf_table_name ||'_'|| tf_date;
tf_table_sql := 'insert into '|| tf_table_black_name || ' select * from '|| tf_table_name || ' t where t.create_dt > to_date('||chr(39)|| tf_date_before ||chr(39)||','||chr(39)||'yyyy-MM-dd'||chr(39)||') and t.create_dt < to_date('||chr(39)||tf_data_nd||chr(39)||','||chr(39)||'yyyy-MM-dd'||chr(39)||')';
dbms_output.put_line('打印' || ':' || tf_table_sql);
tf_table_sql_del:='delete from '||tf_table_name ||' t where t.create_dt > to_date('||chr(39)|| tf_date_before ||chr(39)||','||chr(39)||'yyyy-MM-dd'||chr(39)||') and t.create_dt < to_date('||chr(39)||tf_data_nd||chr(39)||','||chr(39)||'yyyy-MM-dd'||chr(39)||')';
execute immediate tf_table_sql;
execute immediate tf_table_sql_del;
commit;
end proc_migration_data;
使用 ASCII 编码,单引号 ' 的编码是39。这种方法解决了转义时的繁琐,使sql拼接变的方便和清晰。