Tuesday, May 15, 2007

Extract CSV file format in Oracle SQL

How to extract CSV file format data in Oracle SQL Plus.

---10G Solution. On SQL Plus session
alter session set nls_date_format='YYYY-MM-DD';

Session altered.

select regexp_replace(column_value,' *<[^>]*>[^>]*>’,';’)
from table(xmlsequence(cursor(select * from emp)));

=======================

-- Oracle 9i Solution. SQL Plus session.
-- Following sql fail to give EMPTY space for NULL values properly.
-- See PL/SQL solution to handle
SELECT XMLTRANSFORM
(COLUMN_VALUE,
XMLTYPE
('















'
)
) csv
FROM TABLE (XMLSEQUENCE (CURSOR (SELECT *
FROM emp)))
/
=======================================
---- Oracle 9i PL/SQL solution
SQL> VAR cur refcursor

SQL> DECLARE
ctx DBMS_XMLGEN.ctxhandle;
BEGIN
ctx := DBMS_XMLGEN.newcontext ('select * from emp');
DBMS_XMLGEN.setnullhandling (ctx, DBMS_XMLGEN.empty_tag);

OPEN :cur FOR
SELECT (SELECT RTRIM(XMLAGG (XMLELEMENT (c,VALUE (t2),',').EXTRACT('//text()')),',')
FROM TABLE (XMLSEQUENCE (VALUE (t1).EXTRACT ('ROW/*'))) t2) csv
FROM TABLE(XMLSEQUENCE(DBMS_XMLGEN.getxmltype (ctx).EXTRACT('ROWSET/ROW'))) t1;

DBMS_XMLGEN.closecontext(ctx);
END;
/
PL/SQL procedure successfully completed.

SQL> PRINT cur
==================================

2 comments:

Alexis said...

Some days ago I used this tool for sql files-repair your sql server,also program is free,it can help with this problem and retrieve the data, that was considered to be lost,mwill extract housekeeping data from the source database and preview the data, that can be recovered,this tool is a good solution to recover data from corrupted databases in MS SQL Server format,restore databases represent files, like any other documents, they can be easily corrupted by viruses, all sorts of malware, hard drive failures, file system errors, incorrect user actions, etc,supports both data extraction to your hard drive as scripts in SQL format and data export directly to a database in MS SQL Server format.

Alexis said...

There are a lot of good tool for work with MS SQL Server.But I know one not bad tool-repair mdf.It helped me many times as far as I remember.Tool has free status and moreover it can can save recovered data as SQL scripts and supports data extraction via the local area network.