Using OPENROWSET(BULK...)
is the way to go, assuming you can't pre-filter the file.
INSERT INTO table1 (col1, col2, ..., colN)
SELECT col1, col2, ..., colN
FROM OPENROWSET(BULK '<data_file_name>.txt', FORMATFILE = '<format_file_name>.xml') AS a
WHERE ...
As a side benefit, you can optionally transform the data from the file using functions and lookup tables and add joins to other tables for filtering, but you'll need to be mindful of the performance implications.
INSERT INTO table1 (col1, col2, ..., colN)
SELECT a.col1, a.col2, ..., a.colN
FROM OPENROWSET(BULK '<data_file_name>.txt', FORMATFILE = '<format_file_name>.xml') AS a
INNER JOIN ...
ON ...
LEFT JOIN ...
ON ...
WHERE ...
See Import Bulk Data by Using BULK INSERT or OPENROWSET(BULK...)
Note that using OPENROWSET(BULK...)
will require you to create a format file in an XML or non-XML format. Both file formats can be challenging to write by hand and easy to get wrong. Your work will be easier if you can start from a generated file and make the necessary modifications. Generate the format file using the bcp
program. Prefer the XML format (-x
argument).
bcp <table_or_view> format nul -f<format_file_name>.xml -x
See Create a Format File