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

后端 未结 4 1893

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 04:26

    You could always construct the #temp table in dynamic SQL. For example, right now I guess you have been trying:

    CREATE TABLE #tmp(a INT, b INT, c INT);
    
    DECLARE @sql NVARCHAR(1000);
    
    SET @sql = N'BULK INSERT #tmp ...' + @variables;
    
    EXEC master.sys.sp_executesql @sql;
    
    SELECT * FROM #tmp;
    

    This makes it tougher to maintain (readability) but gets by the scoping issue:

    DECLARE @sql NVARCHAR(MAX);
    
    SET @sql = N'CREATE TABLE #tmp(a INT, b INT, c INT);
    
    BULK INSERT #tmp ...' + @variables + ';
    
    SELECT * FROM #tmp;';
    
    EXEC master.sys.sp_executesql @sql;
    

    EDIT 2011-01-12

    In light of how my almost 2-year old answer was suddenly deemed incomplete and unacceptable, by someone whose answer was also incomplete, how about:

    CREATE TABLE #outer(a INT, b INT, c INT);
    
    DECLARE @sql NVARCHAR(MAX);
    
    SET @sql = N'SET NOCOUNT ON; 
    
    CREATE TABLE #inner(a INT, b INT, c INT);
    
    BULK INSERT #inner ...' + @variables + ';
    
    SELECT * FROM #inner;';
    
    INSERT #outer EXEC master.sys.sp_executesql @sql;
    

提交回复
热议问题