October 12, 2010 at 8:57 am
I am trying to import the following file
My\flat\file\delimited
by\backslash
to come in as
My |flat |File |delimited
by |backslash |NULL |NULL
No joy so far. 🙁
What do I need to do???
Please help!
October 12, 2010 at 9:56 am
Since every row doesn't have the name number of columns, you're going to have to import it manually instead of using a flat-file task.
-- first, create a temp table to hold the data
IF OBJECT_ID('tempdb..#Test') IS NOT NULL DROP TABLE #Test;
CREATE TABLE #Test (RowData varchar(max));
-- bulk load the file into one column.
BULK INSERT #Test FROM 'C:\temp\DelimiterTest.txt';
-- add an identity column to this table
ALTER TABLE #Test
ADD RowID INT IDENTITY;
;WITH CTE AS
(
-- get the data from the temp table,
-- and split it out into the delimited parts
SELECT t1.RowID,
t1.RowData,
ds.Item,
ds.ItemNumber
FROM #Test t1
CROSS APPLY dbo.DelimitedSplit8K(t1.RowData, '\') ds
)
-- return the results
SELECT RowID,
RowData,
Column1 = MAX(CASE WHEN ItemNumber = 1 THEN Item ELSE NULL END),
Column2 = MAX(CASE WHEN ItemNumber = 2 THEN Item ELSE NULL END),
Column3 = MAX(CASE WHEN ItemNumber = 3 THEN Item ELSE NULL END),
Column4 = MAX(CASE WHEN ItemNumber = 4 THEN Item ELSE NULL END)
FROM CTE
GROUP BY RowID, RowData
ORDER BY RowID;
Click here for the latest Delimited Split Function.
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
October 13, 2010 at 7:28 am
Wayne
This is great!
Thanks so much!!!
October 14, 2010 at 7:56 am
An alternative is to use PowerShell: you can read in the original flat file, count the number of old delimiters in the header/top-most record, and the replace each of the old delimiters with the required " |" delimiter.
By doing an initial delimiter count in the header/first row, additional delimiters can be added on to the end of subsequent records that are shorter than the header. This could be faster when a larger file is being consumed ... just depends on your situation and what you're trying to do.
October 14, 2010 at 9:17 am
pt9s (10/13/2010)
WayneThis is great!
Thanks so much!!!
You're welcome.
Does it solve your issue?
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
October 14, 2010 at 10:45 am
Like Butta'!!!
U R the MAN!!!
January 3, 2011 at 8:41 am
How would I use bulk insert with a text qualifier?
"Conan", "O'Brien", "123 Cedar Circle, 1", "Los Angeles", "CA", 90025
January 4, 2011 at 7:34 am
pt9s (1/3/2011)
How would I use bulk insert with a text qualifier?"Conan", "O'Brien", "123 Cedar Circle, 1", "Los Angeles", "CA", 90025
You can try the FIELDTERMINATOR option of the BULK INSERT command.
Need an answer? No, you need a question
My blog at https://sqlkover.com.
MCSE Business Intelligence - Microsoft Data Platform MVP
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply