How to BULK INSERT a file into a *temporary* table where the filename is a variable?

后端 未结 4 1886

I have some code like this that I use to do a BULK INSERT of a data file into a table, where the data file and table name are variables:

DECLARE @sql AS NVAR         


        
4条回答
  •  执笔经年
    2020-12-15 03:59

    It is possible to do everything you want. Aaron's answer was not quite complete.

    His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.

    The following code snippet grabs the first line of a file and inserts it into the table @Lines:

    declare @fieldsep char(1) = ',';
    declare @recordsep char(1) = char(10);
    
    declare @Lines table (
        line varchar(8000)
    );
    
    declare @sql varchar(8000) = ' 
        create table #tmp (
            line varchar(8000)
        );
    
        bulk insert #tmp
            from '''+@filename+'''
            with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');
    
        select * from #tmp';
    
    insert into @Lines
        exec(@sql);
    
    select * from @lines
    

提交回复
热议问题