Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Server bulk insert stored procedure

I am using SSMS and trying to create a stored procedure (because it needs to survive batches) ,so i can bulk insert from multiple csv files (one at a time) into specific tables.

So far I have:

CREATE PROCEDURE AddDataToTable @TableName VARCHAR(25), @DataFolderPath VARCHAR(250),
@DataFile VARCHAR(50), @FieldDeterminator VARCHAR(10)
AS
BEGIN
DECLARE @SQL_BULK VARCHAR(MAX)
SET @SQL_BULK =
'BULK INSERT '+@TableName+'
FROM '''+@DataFolderPath+@DataFile+'''
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = '''+@FieldDeterminator+''',
ROWTERMINATOR = ''0x0A'',
TABLOCK
)'
PRINT @SQL_BULK
EXEC @SQL_BULK
END
GO

And using with

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EXEC AddDataToTable 'dbo.People',@DataFolderPath,'\ImdbName.csv',';'

And I get the error:

Msg 911, Level 16, State 4, Procedure AddDataToTable, Line 18 (Batch Start Line 161) Database ‘BULK INSERT dbo’ does not exist. Make sure that the name is entered correctly.

The thing is that I also added a print statement in the procedure and the print result looks like it should with every quote which is:

BULK INSERT dbo.People
FROM 'C:\Users\PC\Desktop\Data\ImdbName.csv'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = ';',
ROWTERMINATOR = '0x0A',
TABLOCK
)

>Solution :

You are using a wrong syntax. Execute the dynamically generated statement like this:

EXEC (@SQL_BULK)

or

DECLARE @err int
EXEC @err = sp_executesql @SQL_BULK
IF @err <> 0 PRINT 'Error found.'

As an additional note, always use QUOTENAME() to prevent possible SQL injection issues, when you generate an SQL Server identifier from an input string:

SET @SQL_BULK = 'BULK INSERT ' + QUOTENAME(@TableName) + ' FROM ... '
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading