Jon
Jon

Reputation: 40062

Using BULK INSERT to map columns

I have a CSV file with 6 millions rows. Each line is made up of the same format eg/

I,h,q,q,3,A,5,Q,3,[,5,Q,8,c,3,N,3,E,4,F,4,g,4,I,V,9000,0000001-100,G9999999990001800000000000001,G9999999990000001100PDNELKKMMCNELRQNWJ010, , , , , , ,D,Z

I have 2 columns in a table.

The first column should be field 27 in the CSV and the second column should be the whole line in the CSV file.

I have tried to set up a format file but cannot get it working.

Is it even possible to do this sort of mapping?

Here is what I have:

BULK INSERT Staging FROM 'C:\Data.txt' 
   WITH 
   (
      FIELDTERMINATOR =',',
      ROWTERMINATOR ='\n',
      KEEPNULLS,
      formatfile='C:\format.fmt'
   )

This is my format file

9.0
2
1       SQLCHAR       0       40     ","     27     Col27               SQL_Latin1_General_CP1_CI_AS
2       SQLCHAR       0       200     "\r\n"  1     Col1               SQL_Latin1_General_CP1_CI_AS

In terms of comparison, I have this working in SQLite which takes 2min 35secs.

Upvotes: 2

Views: 9819

Answers (1)

Chris Townsend
Chris Townsend

Reputation: 3162

You could crack this nut a couple of ways but the way I did it was to bulk insert the WHOLE csv file into a temp table via dynamic SQL:

CREATE TABLE #BulkLoadData(
    RecordData NVARCHAR(max)
)


SET @SQL = 'BULK INSERT #BulkLoadData FROM ''' + @SourceFileFullPath + ''' '
SET @SQL = @SQL + 'WITH (FORMATFILE = ''' + @UPXInputFileBulkLoadFormat + 'UPXInputFileBulkLoadFormat.xml'', TABLOCK, ROWS_PER_BATCH = 2500 ) '

EXECUTE (@SQL)

Then you can insert the data into the target table like this:

INSERT INTO dbo.TargetTable
SELECT dbo.fnParseString(27, ',', RecordData), RecordData

You'll need to create a parse function like so:

CREATE FUNCTION [dbo].[fnParseString]
(
    @Section SMALLINT,
    @Delimiter CHAR,
    @Text VARCHAR(MAX)
)
RETURNS VARCHAR(8000)
AS

BEGIN
DECLARE @startindex NUMERIC(18,0),
     @length NUMERIC(18,0),
     @FieldPosition INT

 SET @FieldPosition = ABS(@Section) - 1
 SET @startindex = 0


 WHILE @FieldPosition != 0
 BEGIN
    SET @FieldPosition = @FieldPosition - 1
     SET @startindex = CHARINDEX(@Delimiter, @Text, @startindex + 1) 
 END     


 SET @Text = SUBSTRING(@Text, @startindex + 1, LEN(@Text) - @startindex)
 SET @Text = SUBSTRING(@Text, 0, CHARINDEX(@Delimiter, @Text))

 RETURN @Text
END

Hope that helps! If you need help with the format file let me know.

Here is the format file contents:

<?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="\n" MAX_LENGTH="8000" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
  </RECORD>
  <ROW>
    <COLUMN SOURCE="1" NAME="RecordData" xsi:type="SQLVARYCHAR"/>
  </ROW>
</BCPFORMAT>

Upvotes: 4

Related Questions