Problem: How to import data
file like (csv or txt or xlsx) into a SQL Server Table?
Solution: BULK
INSERT
There are sometimes where you want to import a data
file into a table, like product prices which comes from the business as excel
or some other data access files. If you don’t have SSIS, Import export wizard.
Syntax:
BULK INSERT
[ database_name . [
schema_name ] . | schema_name . ] [ table_name | view_name ]
FROM
'data_file'
[ WITH
(
[ [ , ] BATCHSIZE =
batch_size ]
[ [ , ]
CHECK_CONSTRAINTS ]
[ [ , ] CODEPAGE =
{ 'ACP' | 'OEM' | 'RAW' | 'code_page' } ]
[ [ , ]
DATAFILETYPE =
{ 'char' |
'native'| 'widechar' | 'widenative' } ]
[ [ , ] DATASOURCE
= 'data_source_name' ]
[ [ , ] ERRORFILE =
'file_name' ]
[ [ , ]
ERRORFILE_DATASOURCE = 'data_source_name' ]
[ [ , ] FIRSTROW =
first_row ]
[ [ , ]
FIRE_TRIGGERS ]
[ [ , ]
FORMATFILE_DATASOURCE = 'data_source_name' ]
[ [ , ]
KEEPIDENTITY ]
[ [ , ] KEEPNULLS
]
[ [ , ]
KILOBYTES_PER_BATCH = kilobytes_per_batch ]
[ [ , ] LASTROW =
last_row ]
[ [ , ] MAXERRORS =
max_errors ]
[ [ , ] ORDER ( {
column [ ASC | DESC ] } [ ,...n ] ) ]
[ [ , ]
ROWS_PER_BATCH = rows_per_batch ]
[ [ , ] ROWTERMINATOR
= 'row_terminator' ]
[ [ , ] TABLOCK
]
-- input file
format options
[ [ , ] FORMAT =
'CSV' ]
[ [ , ] FIELDQUOTE
= 'quote_characters']
[ [ , ] FORMATFILE
= 'format_file_path' ]
[ [ , ]
FIELDTERMINATOR = 'field_terminator' ]
[ [ , ]
ROWTERMINATOR = 'row_terminator' ]
)]
Example:
In this example, I would like to show we can Insert data
into the SQL Server Table from csv file where the data looks like below.
BULK
INSERT dbo.TestBULKInsert
FROM 'C:\Temp\Export
Files\ArticlesPost2017-05-22.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO
--Check
the content of the table.
SELECT *
FROM dbo.TestBULKInsert
GO
--Drop
the table to clean up database.
DROP TABLE dbo.TestBULKInsert
GO
Results:
0 comments:
Post a Comment