Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I'm trying to figure out a way that I can pass a filename into a stored procedure that can import a file. However, after setting up the SQL dynamically, the object can't be found.

DECLARE @fileName varchar(200), 
    @sql varchar(max);

SET @fileName = 'C:\file.csv';

SET @sql = 'SELECT *
    INTO #import
    FROM OPENROWSET(BULK ''' + @fileName + ''',
    FORMATFILE=''C:\format.xml'',
    FIRSTROW = 2) AS a';

EXEC(@sql);

SELECT * INTO #stage
FROM #import;

The result

(27823 row(s) affected)
Msg 208, Level 16, State 0, Line 29
Invalid object name '#tmtImport'.
share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

Use ##import as your table. Global temp table will last for the life of the connection. The #import tables goes out of scope after the exec

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.