I am trying to do a BULK INSERT operation on SQL Server 2008 R2 using a parameter. However, I am having problems that the function expects a STRING where I'm passing it a VARCHAR. My SQL is below.
DECLARE @filepath VARCHAR(30)
DECLARE @current_symbol VARCHAR(30)
DECLARE symbol_cursor CURSOR FOR
SELECT symbol FROM stocks.dbo.description WHERE 1=1
OPEN symbol_cursor;
FETCH NEXT FROM symbol_cursor INTO @current_symbol
WHILE @current_symbol is not null
BEGIN
SET @filepath = 'C:\Users\stkerr\Desktop\stockPricing\' + @current_symbol + '.prices'
BULK
INSERT stocks.dbo.pricing
FROM @filepath
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR=',',
ROWTERMINATOR='\n',
ORDER ( [date], [open], high, low, [close],volume),
ERRORFILE='C:\Users\stkerr\errors.txt'.
)
FETCH NEXT FROM symbol_cursor INTO @current_symbol
END
GO
The problem is popping up when I'm executing the SET @filepath statement.
Any ideas?
In order to specify the file in a variable (@filepath
) to BULK INSERT
, you will need to construct dynamic TSQL and execute it.
e.g.
DECLARE @str_command nvarchar(150)
SET @str_command = 'BULK INSERT [Customer_Sample] FROM ''' + @SourceFilePath +
''' WITH (formatfile = ''' + @FormatFilePath +
''', firstrow =' + cast(@RowNumber as nvarchar) + ')'
EXEC SP_EXECUTESQL @str_command
there is no "string" type in sql. if you're having trouble with the set
statement it's likely because you've given it a maximum length of 30 characters, and your text is longer than that.
if its the From @filepath
thats giving you trouble, its because bulk insert won't take a variable in the from
statement.
overall, i think your option is probably to execute the bulk insert via dynamic sql. build the statement up in a variable and then exec() it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With