In my previous blog I posted to Generate SQL Plus script Dynamically and now I am providing a SQL Script to generate SQL Loader Control File dynamically from SQL script. You need to just run this script in the schema where that table exists for which you want to create the control file and after running the script it will prompt you to enter the Table name and after entering the table name it will generate the Control file for that table. You may need to edit control file after generation but a basic Control File would be created, which could be a very time-saving.
Below is the SQL Plus Script from which you can generate the Control File:
SET ECHO OFF; SET HEAD OFF; SET PAGESIZE 100; SET LINESIZE 100; SET UNDERLINE OFF; SET FEED OFF; SET VER OFF; ACCEPT tblname CHAR PROMPT 'Enter Table Name: '; SPOOL yourtable.ctl SELECT   'LOAD DATA APPEND INTO TABLE '     || '&tblname'     || ' FIELDS TERMINATED BY '',''  OPTIONALLY ENCLOSED BY '''     || CHR (34)     || ''' TRAILING NULLCOLS ('  FROM DUAL UNION ALL SELECT tab_cols  FROM (  SELECT column_name || ',' tab_cols       FROM user_tab_cols       WHERE table_name = '&tblname'     ORDER BY column_id) UNION ALL SELECT ')' FROM DUAL / SPOOL OFF /
Suppose if you will generate it for Scott.Emp Table, then the output of the control file would be as following:
LOAD DATA Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â APPEND INTO TABLE EMP Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â FIELDS TERMINATED BY ',' Â OPTIONALLY ENCLOSED BY '"' Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â TRAILING NULLCOLS ( EMPNO, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ENAME, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â JOB, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â MGR, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â HIREDATE, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â SAL, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â COMM, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â DEPTNO Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â )
See also:
Use the below query:
SELECT 'LOAD DATA
APPEND INTO TABLE '
|| '&tblname'
|| '
FIELDS TERMINATED BY '','' OPTIONALLY ENCLOSED BY '''
|| CHR (34)
|| '''
TRAILING NULLCOLS ('
FROM DUAL
UNION ALL
SELECT CASE WHEN rn = c THEN RTRIM (tab_cols, ',') ELSE tab_cols END tab_cols
FROM ( SELECT column_name || ',' tab_cols,
ROWNUM rn,
(SELECT MAX (column_id)
FROM user_tab_cols
WHERE table_name = '&tblname')
c
FROM user_tab_cols
WHERE table_name = '&tblname'
ORDER BY column_id)
UNION ALL
SELECT ')' FROM DUAL
How to remove the last comma from the column select list