Reading CSV files in MSSQL

bcp utility

The bcp utility bulk copies data between an instance of Microsoft SQL Server and a data file in a user-specified format. See bsp utility on Technet.

Allow xp_cmdshell
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO

Format file

Read more details on Technet

Structure
version
Number of columns
col number, file data type, prefix length, data length, terminator, table col order, table col name, file collation
Example
10.0
3
1       SQLCHAR             0       12     ","     1     Col1                                       ""
2       SQLCHAR             0       12     ","     2     Col2                                       SQL_Latin1_General_CP1_CI_AS
3       SQLCHAR             0       12     ","     3     Col3                                       SQL_Latin1_General_CP1_CI_AS

Data types

Generating format file
EXEC xp_cmdshell 'bcp DB..MyTable format nul -c -f c:\formatFile.txt -T'

Reading the file

EXEC xp_cmdshell 'bcp DB..MyTable in c:\DataSource.csv -f c:\formatFile.txt -T'

Bulk insert

bulk INSERT dbo.a FROM 'c:\Projects\DataSet4assign.csv' WITH (formatfile = 'c:\Projects\formatFile.txt')

Sources

programming/mssql/readingcsv.txt · Last modified: 2018-06-21 19:48 (external edit)
CC Attribution-Noncommercial-Share Alike 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0