SCRIPT TO GENERATE INSERT STATEMENTS:
/*
|| File:
|| Dump.SQL
|| Description:
|| Creates insert statements for existing data
|| Author:
|| Ramesh K Meda.
||
*/
set pages 0
set lines 132
set verify off
set feedback off
accept sTab prompt 'Enter table name: '
column MaxColId noprint new_val sMaxColId
select max(column_id) MaxColId
from user_tab_columns
where table_name = upper('&sTab')
/
spool junk.sql
prompt Select -----prompt 是为了生成select 'select' fromXXX
select decode(column_id, 1, '''insert into &sTab. Values ('' || chr(10) || ')
|| decode(column_id, 1, '', ' || ')
|| decode(column_id, 1, '', ''','' ||')
|| 'decode(' || column_name || ', null, ''Null'',' || '''''''''|| ' ||
column_name || ' || ''''''''' || ')'
|| '|| chr(10)'
|| decode(column_id, &sMaxColId, ' || '')'' || chr(10) || ''/'' ', null)
from user_tab_columns
where table_name = upper('&sTab')
order by column_id
/
Prompt from &sTab.;
Prompt /
spool off
spool &sTab..dat
spool off
Prompt Output spooled to &sTab..dat
SCRIPT TO GENERATE CONTROL FILE AND DATA FILE FOR USE WITH SQL*LOADER:
/*
||
|| Description:
|| Given a tablename generates
|| 1. Flat ascii file with delimiters
|| 2. SQL*Load control file to load the data
||
*/
set echo off
set doc off
set pagesize 0
set feedback off
set verify off
set pause off
accept vtbl_name prompt 'Enter table name: '
define ColumnDelim = "|"
define DateFormat = "yyyymmddhhmiss"
define dataname = &&vtbl_name..dat
spool data.sql
prompt ALTER SESSION SET NLS_DATE_FORMAT="&DateFormat.";;
--
-- Header info
--
prompt /*
prompt || Script Name: data.sql
prompt || Author: Ramesh K Meda
prompt || Date: Feb 1995 (Does day matter?)
prompt || Copyright info: Feel free to copy!
prompt || Fees: As you please!
prompt */
prompt clear columns
--
-- Set up column formats
--
select 'column ' || column_name || ' format ' ||
DECODE (data_type,
'DATE', 'A14'
,'NUMBER' ,
decode (data_scale, 0,
rpad('0', nvl(data_precision - nvl(data_scale,0), 38), '0')
, rpad('0', nvl(data_precision - nvl(data_scale,0), 38), '0')
|| '.' ||
rpad('0', nvl(data_scale, 5), '0'))
,'A' || data_length
)
from user_tab_columns
where table_name = UPPER('&&vtbl_name')
order by column_id;
--
-- Set Line size to export data
--
select 'set linesize '||
sum(DECODE(data_type
,'DATE', 25
,'NUMBER', nvl(data_precision,45) + 5
, data_length + 5
)
)
from user_tab_columns
where table_name = UPPER('&&vtbl_name');
prompt set echo off
prompt set pagesize 0
prompt set space 0
prompt set feedback off
prompt set verify off
prompt set pause off
prompt set termout off
prompt spool &dataname
prompt select
select decode(column_id, 1, ' ', ',')
, column_name
, ',''&ColumnDelim.'''
from user_tab_columns
where table_name = upper('&&vtbl_name')
order by column_id
/
prompt from &&vtbl_name;;
prompt spool off
prompt set pagesize 15
prompt set feedback on
prompt set verify on
prompt set heading on
prompt set linesize 80
prompt set termout on
spool off
--
-- Create control file
--
prompt Generating control file for SQL*Load
set lines 100
spool &&vtbl_name..ctl
prompt
prompt load data
prompt replace
prompt into table &vTbl_Name
prompt (
select decode (column_id, 1, ' ', ',') ||
column_name ||
chr(9) ||
decode(data_type, 'DATE', ' DATE "&DateFormat"', ' CHAR ') ||
chr(9) ||
' terminated by ''&ColumnDelim.'' ' ||
' nullif ' ||
column_name ||
' = blanks '
from user_tab_columns
where table_name = upper('&&vtbl_name')
order by column_id
/
prompt )
spool off
clear scree
prompt Generating data file
prompt Files generated:
prompt SQL script: data.sql
prompt data file: &&vtbl_name..dat
prompt control: &&vtbl_name..ctl
Explains how to get data from an existing table to flat file usable by SQL*Loader.
SCOPE
DBAs and Developers.
DETAILS
The script at end of this bulletin spools STRING, NUMBER and DATE data from tables in the format of a SQL*Loader controlfile. If you remove the first "control section" of the spool file, you will have a 'coma separated values' formatted file.
Syntax:
sqlplus username/password @csv <table_owner> <table_name> <list_of_columns>
or if you already are in sqlplus:
@csv <table_owner> <table_name> <list_of_columns>
e.g.:
sqlplus scott/tiger@orcl @csv scott emp "*"
or
sqlplus scott/tiger@matu @csv scott emp 'empno, ename'
or if you already are in sqlplus:
@csv scott emp 'empno, ename'
It will generate file <table_name>.lst.
You can use file <table_name>.lst as control file for sqlload into new table:
export NLS_DATE_FORMAT=DD.MM.YYYY HH24:MI:SS
sqlldr username/password control=<table_name>.lst
e.g.:
export NLS_DATE_FORMAT=DD.MM.YYYY HH24:MI:SS
sqlldr test/test@orcl control=emp.lst
WARNING:
-
You have to set "NLS_DATE_FORMAT=DD.MM.YYYY HH24:MI:SS" in your environment for sqlloader session.
-
You have to have pre-created tables in your target database for sqlloader. You can follow steps from Note 123851.1 to create them.
HINT: You can generate script invoking this script for every table of user SCOTT by:
spool scott_tables
select '@csv scott '||table_name||' * ' from dba_tables where owner='SCOTT';
spool off
You have to remove "quit" at end of script csv.sql in this case.
============ Script csv.sql ==================
set serveroutput on size 1000000
set pages 0
set colsep ''
set term off
set wrap on
set verify off
set heading off
set sqlprompt ''
set showmode off
set feedback off
spool csv.tmp
declare
type VMrec is record(
column_name all_tab_columns.column_name%type,
data_type all_tab_columns.data_type%type,
data_length all_tab_columns.data_length%type
);
r VMrec;
colNum number;
myColumn all_tab_columns.column_name%type;
r_owner varchar2(30) := '&1';
r_table_name varchar2(30) := '&2';
clist varchar2(4000) := '&3';
ls number := 0;
starting boolean := true;
begin
if clist = '*' then
clist:='';
for r in (select column_name from all_tab_columns
where owner=upper(r_owner)
and table_name=upper(r_table_name))
loop
if starting then
starting:=false;
else
clist:=clist||',';
end if;
clist:=clist||r.column_name;
end loop;
else
clist:=upper(clist);
end if;
starting:=true;
loop
colNum:=instr(clist,',');
if colNum>0 then
myColumn:=substr(clist,0,colNum-1);
clist:=substr(clist,colNum+1,4000);
else
myColumn:=clist;
clist:='';
end if;
myColumn:=rtrim(ltrim(myColumn));
if myColumn is null then
exit;
end if;
select column_name, data_type, data_length into r
from all_tab_columns
where table_name=upper(r_table_name)
and owner=upper(r_owner)
and column_name = myColumn;
if(r.data_type='DATE') then
ls:=ls+21;
else
ls := ls + r.data_length;
end if;
end loop;
dbms_output.put_line('set linesize '||ls);
dbms_output.put_line('set colsep '||chr(39)||chr(39)); -- dont put space between columns
dbms_output.put_line('set wrap on'); -- don't truncate long lines. Wrap them.
dbms_output.put_line('set verify off'); -- don't list sql statement
dbms_output.put_line('set heading off'); -- don't show column heading
dbms_output.put_line('set sqlprompt '||chr(39)||chr(39)); -- supress prompt
dbms_output.put_line('set showmode off'); -- dont show old and new value
dbms_output.put_line('set feedback off'); -- dont show number of rows returned by query
dbms_output.put_line('select ');
starting:=true;
clist:='&3';
if clist = '*' then
-- to ensure order of columns
clist:='';
for r in (select column_name from all_tab_columns
where owner=upper(r_owner)
and table_name=upper(r_table_name))
loop
if starting then
starting:=false;
else
clist:=clist||',';
end if;
clist:=clist||r.column_name;
end loop;
else
clist:=upper(clist);
end if;
starting:=true;
loop
colNum:=instr(clist,',');
if colNum>0 then
myColumn:=substr(clist,0,colNum-1);
clist:=substr(clist,colNum+1,4000);
else
myColumn:=clist;
clist:='';
end if;
myColumn:=rtrim(ltrim(myColumn));
if myColumn is null then
exit;
end if;
select column_name, data_type, data_length into r
from all_tab_columns
where table_name=upper(r_table_name)
and owner=upper(r_owner)
and column_name = myColumn;
if starting then
starting:=false;
else
dbms_output.put_line(','||'chr(44)'||',');
end if;
if instr(r.data_type,'CHAR')>0 then
dbms_output.put_line('chr(34),'||r.column_name||',chr(34)');
else if r.data_type='NUMBER' then
dbms_output.put_line(r.column_name);
else if r.data_type='DATE' then
dbms_output.put_line('chr(34),'||'to_char('||r.column_name||','||chr(39)||'DD.MM.YYYY HH24:MI:SS'||chr(39)||')'||',chr(34)');
end if;
end if;
end if;
end loop;
dbms_output.put_line(' from '||r_table_name||';');
exception
when others then
dbms_output.put_line('Encontered: '||sqlerrm||' ... for '||r_owner||'.'||r_table_name||'.'||myColumn);
end;
/
spool off
spool &2
declare
r_owner varchar2(30) := '&1';
r_table_name varchar2(30) := '&2';
clist varchar2(4000) := '&3';
starting boolean := true;
begin
if clist = '*' then
clist:='';
for r in (select column_name from all_tab_columns
where owner=upper(r_owner)
and table_name=upper(r_table_name))
loop
if starting then
starting:=false;
else
clist:=clist||',';
end if;
clist:=clist||chr(39)||r.column_name||chr(39);
end loop;
else
clist:=replace(clist,' ','');
clist:=upper(clist);
clist:=replace(clist,',',chr(39)||','||chr(39));
clist:=chr(39)||clist||chr(39);
end if;
starting:=true;
dbms_output.put_line('LOAD DATA INFILE *');
dbms_output.put_line('INTO TABLE '||r_table_name);
dbms_output.put_line('FIELDS TERMINATED BY '||chr(39)||','||chr(39));
dbms_output.put_line('OPTIONALLY ENCLOSED BY '||chr(39)||chr(34)||chr(39));
dbms_output.put_line('(');
for r in (select column_name, data_type from all_tab_columns
where table_name=upper(r_table_name)
and owner=upper(r_owner)
and instr(clist,column_name)>0)
loop
if starting then
starting:=false;
else
dbms_output.put_line(',');
end if;
dbms_output.put_line(r.column_name);
end loop;
dbms_output.put_line(') BEGINDATA ');
end;
/
quit
============ End of script csv.sql ==================
Script to generate SQL*Loader control file.
SOLUTION
Requirements
Execution Environment: SQL*Plus
Access Privileges: SELECT privileges on the table
Usage: sqlplus / @control.sql
Instructions: PROOFREAD THIS SCRIPT BEFORE USING IT! Due to differences in the way text editors, e-mail packages, and operating systems handle text formatting (spaces, tabs, and carriage returns), this script may not be in an executable state when you first receive it. Check over the script to ensure that errors of this type are corrected. The script will produce an output file named .ctl. This file can be viewed in a browser or uploaded for support analysis.
Configuring
This script prepares a SQL*Loader control file for a table already existing in the database. The script accepts the table name and automatically creates a file with the table name and extension 'ctl'. This is specially useful if you have the DDL statement to create a particular table and have a free-format ASCII-delimited file but have not yet created a SQL*Loader control file for the loading operation.
Default choices for the file are as follows (alter to your needs):
Delimiter: comma (',')
INFILE file extension: .dat
DATE format: 'MM/DD/YY'
You may define the Loader Data Types of the other Data Types by revising the DECODE function pertaining to them.
Please note: The name of the table to be unloaded needs to be provided when the script is executed as follows:
SQL> start control.sql emp
Example:
SQL> start control.sql emp
LOAD DATA
INFILE 'EMP.dat'
INTO TABLE EMP
FIELDS TERMINATED BY ','
(
EMPNO
, ENAME
, JOB
, MGR
, HIREDATE DATE "MM/DD/YY"
, SAL
, COMM
, DEPTNO
)
Instructions
No special instructions.
Sample Code
SQL*Plus script control.sql:
set echo off
set heading off
set verify off
set feedback off
set show off
set trim off
set pages 0
set concat on
set lines 300
set trimspool on
set trimout on
spool &1..ctl
select 'LOAD DATA'||chr (10)||
'INFILE '''||lower (table_name)||'.dat'''||chr (10)||
'INTO TABLE '||table_name||chr (10)||
'FIELDS TERMINATED BY '','''||chr (10)||
'TRAILING NULLCOLS'||chr (10)||'('
from all_tables
where table_name = upper ('&1');
select decode (rownum, 1, ' ', ' , ')||
rpad (column_name, 33, ' ')||
decode (data_type, 'VARCHAR2', 'CHAR NULLIF ('||column_name||'=BLANKS)',
'FLOAT', 'DECIMAL EXTERNAL NULLIF('||column_name||'=BLANKS)',
'NUMBER', decode (data_precision, 0, 'INTEGER EXTERNAL NULLIF ('||column_name||'=BLANKS)',
decode (data_scale, 0, 'INTEGER EXTERNAL NULLIF ('||column_name||'=BLANKS)',
'DECIMAL EXTERNAL NULLIF ('||column_name||'=BLANKS)')),
'DATE', 'DATE "MM/DD/YY" NULLIF ('||column_name||'=BLANKS)', null)
from user_tab_columns
where table_name = upper ('&1')
order by column_id;
select ')'
from sys.dual;
spool off
Sample Output
No sample output included.