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

后端 未结 4 1873

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:16

    Sorry to dig up an old question but in case someone stumbles onto this thread and wants a quicker solution.

    Bulk inserting a unknown width file with \n row terminators into a temp table that is created outside of the EXEC statement.

    DECLARE     @SQL VARCHAR(8000)
    
    IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
    BEGIN
        DROP TABLE #BulkInsert
    END
    
    CREATE TABLE #BulkInsert
    (
        Line    VARCHAR(MAX)
    )
    
    SET @SQL = 'BULK INSERT #BulkInser FROM ''##FILEPATH##'' WITH (ROWTERMINATOR = ''\n'')'
    EXEC (@SQL)
    
    SELECT * FROM #BulkInsert
    

    Further support that dynamic SQL within an EXEC statement has access to temp tables outside of the EXEC statement. http://sqlfiddle.com/#!3/d41d8/19343

    DECLARE     @SQL VARCHAR(8000)
    
    IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
    BEGIN
        DROP TABLE #BulkInsert
    END
    
    CREATE TABLE #BulkInsert
    (
        Line    VARCHAR(MAX)
    )
    INSERT INTO #BulkInsert
    (
        Line
    )
    SELECT 1
    UNION SELECT 2
    UNION SELECT 3
    
    SET @SQL = 'SELECT * FROM #BulkInsert'
    EXEC (@SQL)
    

    Further support, written for MSSQL2000 http://technet.microsoft.com/en-us/library/aa175921(v=sql.80).aspx

    Example at the bottom of the link

    DECLARE @cmd VARCHAR(1000), @ExecError INT
    CREATE TABLE #ErrFile (ExecError INT)
    SET @cmd = 'EXEC GetTableCount ' + 
    '''pubs.dbo.authors''' + 
    'INSERT #ErrFile VALUES(@@ERROR)'
    EXEC(@cmd)
    SET @ExecError = (SELECT * FROM #ErrFile)
    SELECT @ExecError AS '@@ERROR'
    

提交回复
热议问题