功能:生成某一用户下所有数据表数据的insert语句,放入d:\insert.sql文件。
限制:只支持number、char、varchar2、date、long、clob数据类型。
提示:数据量小还可以,大了就别用这种方式了,会很慢。
/* Formatted on 2012-12-27 20:56:24 (QP5 v5.185.11230.41888) */
CREATEORREPLACE DIRECTORY mydir AS'D:\';
DECLARE
ROW_NUMBER NUMBER := 0;
col_str VARCHAR2 (32767) := '';
select_str VARCHAR2 (32767) := '';
ins_tab DBMS_SQL.varchar2_table;
l_count INT := 0;
log_file UTL_FILE.file_type;
BEGIN
log_file := UTL_FILE.fopen ('MYDIR', 'insert.sql', 'w');
UTL_FILE.put_line (log_file, 'set define off;');
FOR x IN (SELECT table_name FROM user_tables)
LOOP
EXECUTE IMMEDIATE 'select count(*) from ' || x.table_name
INTO ROW_NUMBER;
IF ROW_NUMBER > 0
THEN
col_str := '';
select_str := '';
FOR y IN ( SELECT column_name, data_type
FROM user_tab_columns
WHERE table_name = x.table_name AND data_type != 'BLOB'
ORDERBY column_id)
LOOP
col_str := col_str || y.column_name || ',';
IF y.data_type = 'NUMBER'
THEN
select_str :=
select_str
|| 'decode('
|| y.column_name
|| ',null,''null'','
|| y.column_name
|| ')||'',''||';
ELSE
IF y.data_type IN ('CHAR', 'VARCHAR2', 'LONG', 'CLOB')
THEN
select_str :=
select_str
|| 'decode('
|| y.column_name
|| ',null,''null'',''''''''||replace('
|| y.column_name
|| ','''''''','''''''''''')||'''''''')||'',''||';
ELSE
IF y.data_type = 'DATE'
THEN
select_str :=
select_str
|| 'decode('
|| y.column_name
|| ',null,''null'',''to_date(''''''||'
|| 'to_char('
|| y.column_name
|| ',''yyyy-mm-dd hh24:mi:ss'')||'''
|| '''||'''''',''''yyyy-mm-dd hh24:mi:ss'''')'')||'',''||';
END IF;
END IF;
END IF;
END LOOP;
col_str := 'insert into ' || x.table_name || ' (' || col_str;
col_str := SUBSTR (col_str, 1, LENGTH (col_str) - 1) || ') values (';
select_str :=
'select '''
|| col_str
|| ''' ||'
|| SUBSTR (select_str, 1, LENGTH (select_str) - 7)
|| '|| ''); from '
|| x.table_name;
-- dbms_output.put_line(select_str);
EXECUTE IMMEDIATE select_str BULK COLLECT INTO ins_tab;
l_count := ins_tab.COUNT;
UTL_FILE.put_line (log_file, '');
UTL_FILE.put_line (log_file, '-- table name: ' || x.table_name);
FOR i IN 1 .. l_count
LOOP
UTL_FILE.put_line (log_file, ins_tab (i));
END LOOP;
END IF;
END LOOP;
UTL_FILE.put_line (log_file, '');
UTL_FILE.put_line (log_file, 'commit;');
UTL_FILE.fclose (log_file);
END;
/
--转自