Bulk Insert Optimization with Stored Procedures
When faced with the need to efficiently import large amounts of data, consider employing the BULK INSERT command. In this scenario, the objective is to create a stored procedure that performs the bulk insert operation.
Upon attempting to create the stored procedure, however, an error message appears, indicating incorrect syntax near "@filepath" and "WITH." This error stems from an inherent limitation of the BULK INSERT command: it cannot accept a file name as a variable.
To resolve this issue, consider constructing the BULK INSERT statement as a string with a fixed file name, followed by executing it using dynamic SQL. Here's an example:
DECLARE @filepath nvarchar(500) SET @filepath = N'e:-digit Commercial.csv' DECLARE @bulkinsert NVARCHAR(2000) SET @bulkinsert = N'BULK INSERT ZIPCodes FROM ''' + @filepath + N''' WITH (FIRSTROW = 2, FIELDTERMINATOR = '','', ROWTERMINATOR = ''\n'')' EXEC sp_executesql @bulkinsert
By following this approach, you can overcome the limitation of BULK INSERT and efficiently import data into your database.
The above is the detailed content of How Can I Use Stored Procedures to Optimize Bulk Inserts When Facing `BULK INSERT` Syntax Errors?. For more information, please follow other related articles on the PHP Chinese website!