BULK INSERT with variable file name

2020-02-05 01:34发布

i am trying to bulk insert into Db using sql server 2005

Below is the code.

declare @path varchar(500) 
set @path = 'E:\Support\test.csv'; 

Create table #mytable( name varchar(max), class varchar(max), roll varchar(max) )

BULK INSERT #mytable FROM @path <-- Error line
WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ); 
Go 
select * from #mytable
drop table #mytable

Problem: issue is that my file path is dynamic and comes from a variable instead of hard coding which is not working If i change the error line to below it works

 BULK INSERT #mytable FROM 'E:\Support\test.csv'; 

Please advise how to fix this

2条回答
可以哭但决不认输i
2楼-- · 2020-02-05 02:15
DECLARE @path varchar(50) = 'D:\ARQUIVOS_CARGAS\CABOS\FILE.prn'
DECLARE @SQL_BULK VARCHAR(MAX)
SET @SQL_BULK = 'BULK INSERT #TAB FROM ''' + @path + ''' WITH
        (
        CODEPAGE = ''ACP'',
        FIRSTROW = 1,
        FIELDTERMINATOR = ''tab'',
        ROWTERMINATOR = ''0x0a'',
        KEEPNULLS
        )'

EXEC (@SQL_BULK)
查看更多
家丑人穷心不美
3楼-- · 2020-02-05 02:22

Try to use Dynamic SQL:

declare @sql varchar(max)
set @sql = 'BULK INSERT #mytable FROM ''' + @path + ''' WITH ...
exec (@sql)
查看更多
登录 后发表回答