4

I am using BULK INSERT to read a csv file in SQL Server. Is there a way to keep the first row as column name while I am reading the file?

If not, after reading the data from the csv (from second row), how can I add column names to it?

Any help/comments/suggestions are much appreciated.

Paul White
95.3k30 gold badges439 silver badges689 bronze badges
asked Nov 5, 2018 at 13:34
0

2 Answers 2

1

If not, after reading the data from the csv (from second row), how can I add column names to it?

I would put your focus here. First, create your table with yoru column names, data types, etc.

create table myTable (column1 <datatype>, column2 <datatype>)

Then, bulk insert into it but ignore the first row.

bulk insert myTable
 from 'C:\somefile.csv',
 with( firstrow = 2,
 fieldterminator = ',',
 rowterminator = '\n')

If it's dynamic, then you may want to look into openrowset.

answered Nov 5, 2018 at 14:15
1

Assuming you are importing a standard CSV, you can dynamically create the table as such:

DECLARE @sql NVARCHAR(MAX)
DECLARE @filePath NVARCHAR(MAX) = 'C:/SomeFolder/yourImportFile.csv'
DECLARE @tableName NVARCHAR(MAX) = 'yourTableName'
DECLARE @colString NVARCHAR(MAX)
SET @sql = 'SELECT @res = LEFT(BulkColumn, CHARINDEX(CHAR(10),BulkColumn)) FROM OPENROWSET(BULK ''' + @filePath + ''', SINGLE_CLOB) AS x'
exec sp_executesql @sql, N'@res NVARCHAR(MAX) output', @colString output;
SELECT @sql = 'DROP TABLE IF EXISTS ' + @tableName + '; CREATE TABLE [dbo].[' + @tableName + ']( ' + STRING_AGG(name, ', ') + ' ) '
FROM (
 SELECT ' [' + value + '] nvarchar(max) ' as name
 FROM STRING_SPLIT(@colString, ',')
) t
EXECUTE(@sql)

and then bulk insert the data as @scsimon suggested:

BULK INSERT dbo.yourTableName.
FROM 'C:/SomeFolder/yourImportFile.csv'
WITH ( 
 FORMAT='CSV', 
 FIRSTROW = 2, 
 ROWTERMINATOR = '\n', 
 FIELDQUOTE= '"',
 TABLOCK 
)
answered Dec 10, 2019 at 14:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.