WITH COLUMN_DEFINITION AS (
SELECT
    TABLE_NAME,
    COLUMN_NAME,
    CASE
        WHEN (DATA_TYPE= 'NUMBER' AND DATA_SCALE = 0 AND DATA_PRECISION <= 9) THEN 'INTEGER'
        WHEN (DATA_TYPE= 'NUMBER' AND DATA_SCALE = 0 AND DATA_PRECISION <= 18) THEN 'BIGINT'
        WHEN (DATA_TYPE= 'NUMBER' AND DATA_SCALE = 0 AND DATA_PRECISION >= 19) THEN 'DECIMAL(' || DATA_PRECISION || ',0)'
        WHEN (DATA_TYPE= 'NUMBER' AND DATA_SCALE > 0)  THEN 'DECIMAL(' || DATA_PRECISION || ',' || DATA_SCALE ||')'
        WHEN (DATA_TYPE= 'NUMBER' AND nvl(DATA_SCALE,0) = 0 AND nvl(DATA_PRECISION,0) = 0) THEN 'DECIMAL(38,18)'
        WHEN DATA_TYPE= 'CHAR' THEN 'VARCHAR(' || DATA_LENGTH || ')'
        WHEN DATA_TYPE= 'VARCHAR' THEN 'VARCHAR(' || DATA_LENGTH || ')'
        WHEN DATA_TYPE= 'VARCHAR2' THEN 'VARCHAR(' || DATA_LENGTH || ')'
        WHEN DATA_TYPE= 'DATE' THEN 'TIMESTAMP'
        WHEN DATA_TYPE= 'DATETIME' THEN 'TIMESTAMP'
        WHEN DATA_TYPE LIKE 'TIMESTAMP%' THEN 'TIMESTAMP'
        WHEN DATA_TYPE= 'LONG' THEN 'TEXT'
        WHEN DATA_TYPE= 'CLOB' THEN 'TEXT'
        WHEN DATA_TYPE LIKE '%RAW%' THEN 'TEXT'
        WHEN DATA_TYPE= 'NCHAR' THEN 'NCHAR(' || DATA_LENGTH || ')'
        WHEN DATA_TYPE= 'NVARCHAR' THEN 'NVARCHAR(' || DATA_LENGTH || ')'
        ELSE DATA_TYPE || '(' || DATA_LENGTH || ')'
        END AS REDSHIFT_COLUMN_DEFINITION
FROM ALL_TAB_COLUMNS
WHERE
    OWNER= 'SCHEMA_NAME'
    AND TABLE_NAME = 'TABLE_NAME'
ORDER BY DATA_TYPE,COLUMN_ID
)

SELECT 'CREATE TABLE ('||MAX(TABLE_NAME) AS TEXT FROM COLUMN_DEFINITION
UNION ALL
SELECT '    '||COLUMN_NAME||' '||REDSHIFT_COLUMN_DEFINITION || ', ' AS TEXT FROM COLUMN_DEFINITION
UNION ALL
SELECT ') ;' AS TEXT FROM DUAL;
