Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS SQL Bulk Insert

I have a requirement to insert a large 2 GB CSV file into my MS SQL database. most of the rows in this is not required to insert. I did not find anything to filter rows while doing bulk insert.I am using MS SQL bulk insert command to do this. Is there any option to filter rows on mySQL/MSSQL/Oracle on bulk insert?

BULK INSERT payroll.t_allowance
   FROM 'f:\orders\lineitem.csv'
   WITH 
      (
         FIELDTERMINATOR =' |',
         ROWTERMINATOR =' |\n'
      );
like image 202
Robi Avatar asked Oct 31 '15 03:10

Robi


People also ask

Can we do bulk insert in SQL?

BULK INSERT loads data from a data file into a table. This functionality is similar to that provided by the in option of the bcp command; however, the data file is read by the SQL Server process. For a description of the BULK INSERT syntax, see BULK INSERT (Transact-SQL).

How can I insert more than 1000 rows in SQL Server?

The number of rows that you can insert at a time is 1,000 rows using this form of the INSERT statement. If you want to insert more rows than that, you should consider using multiple INSERT statements, BULK INSERT or a derived table.


2 Answers

You can use OPENROWSET with BULK option:

SELECT *
FROM OPENROWSET(BULK 'f:\orders\lineitem.csv', 
                FORMATFILE= 'f:\orders\format.xml') AS a
WHERE ... 

format.xml is a file where you configure delimeters, column names, terminators etc: https://msdn.microsoft.com/en-us/library/ms178129.aspx

like image 138
Giorgi Nakeuri Avatar answered Nov 18 '22 02:11

Giorgi Nakeuri


To avoid the complexities of the format file, and with some other trade-offs, you can create a staging table, BULK INSERT the staging table, and use INSERT...SELECT to load the target table from the staging table.

-- Create a temporary staging table with the same column names and data types, but no indexes
-- Alternatively, use CREATE TABLE
-- When using a permanent table, use TRUNCATE TABLE
SELECT *
INTO #stage
FROM payroll.t_allowance
WHERE 1 = 0;

-- Bulk load the staging table
-- Use the TABLOCK hint to achieve minimally logged inserts
BULK INSERT #stage
FROM 'f:\orders\lineitem.csv'
WITH (TABLOCK, FIELDTERMINATOR = ' |', ROWTERMINATOR = ' |\n');

-- Load the target table from the staging table
INSERT INTO payroll.t_allowance
SELECT s.*
FROM #stage AS s
WHERE...;

-- Drop the staging table
-- or use TRUNCATE TABLE for a permanent table
DROP TABLE #stage;
like image 27
Mark Chesney Avatar answered Nov 18 '22 02:11

Mark Chesney