How to parse data from a CLOB in SQL Server?
-
15-04-2021 - |
Domanda
I would like to use OPENROWSET with the BULK command to load data into SQL Server as a CLOB, and as a second step to parse the CLOB and load read the data as a table.
E.g.:
SELECT BulkColumn
FROM OPENROWSET (BULK 'c:\somedir\somefile.txt', SINGLE_CLOB) TheFile
yields:
BulkColumn
Col1,Col2,Col3,1,2,3,1,2,3,1,2,3,1,2,3
I want to select this as:
Col1 Col2 Col3
1 2 3
1 2 3
1 2 3
Soluzione
Create a format file and use OPENROWSET or BULK INSERT to import data from text file. Example format.xml:
<?xml version="1.0" ?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RECORD>
<FIELD ID="1" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="1" />
<FIELD ID="2" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="1" />
<FIELD ID="3" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="1" />
</RECORD>
<ROW>
<COLUMN SOURCE="1" NAME="Col1" xsi:type="SQLNVARCHAR" />
<COLUMN SOURCE="2" NAME="Col2" xsi:type="SQLNVARCHAR" />
<COLUMN SOURCE="3" NAME="Col3" xsi:type="SQLNVARCHAR" />
</ROW>
</BCPFORMAT>
This is the key line:
<FIELD ID="3" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="1" />
where the terminator char is "," and not "\r\n", if the data is in a single line.
Example OPENROWSET:
INSERT INTO [your_table]
SELECT [text_file].[Col1],
[text_file].[Col2],
[text_file].[Col3]
FROM OPENROWSET(
BULK N'c:\somedir\somefile.txt',
FORMATFILE = N'c:\somedir\format.xml',
FIRSTROW = 1) AS [text_file]
Example BULK INSERT:
BULK INSERT [your_table]
FROM N'c:\somedir\somefile.txt'
WITH (FORMATFILE = N'c:\somedir\format.xml')
Altri suggerimenti
Don't import it as OPENROWSET..BULK
You can use BULK INSERT to import it as columns or OPENROWSET by itself
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow