1

I am trying to create a temp table on Microsoft SQL Server 2014 using a variable.

DECLARE @TableName VARCHAR(50)
SET @TableName = 'MyShema.MyTable'

EXEC('SELECT * INTO #temp FROM ' + @TableName)
SELECT * FROM #temp

However, the last line, SELECT * FROM #temp gives Invalid object name '#temp. Can anyone please tell me how I can fix it? Thank you!

2
  • What are you trying to accomplish? Commented Jan 18, 2017 at 20:59
  • There is a mapping table that contains source file names and destination tables for bulkinsert. Before bulkinsert, some data clean up in a temp table is necessary. So I am just trying to loop through this mapping list and set @TableName and create a temp table one by one. Commented Jan 18, 2017 at 21:16

3 Answers 3

2
DECLARE @TableName1 VARCHAR(50)

SET @TableName1 = 'dbo.encounter'

EXEC('SELECT * INTO ##temp FROM ' + @TableName1)

SELECT * FROM ##temp
Sign up to request clarification or add additional context in comments.

Comments

1

Check out this link.

http://www.sommarskog.se/dynamic_sql.html#Dyn_table

The temp table created in a dynamic SQL statement is dropped at the exit of that statement. That is why you got the error.

Comments

0
  DECLARE @sql NVARCHAR(MAX);

  SET @sql = N'SELECT * INTO #temp FROM from MyShema.MyTable ; SELECT * FROM #tmpA';

EXEC sp_executesql @sql

3 Comments

This gives the same error Invalid object name '#tmp' Would you advice how can i use a variable @TableName to perform the task?
There is a typo in the string. You cannot see the table #tmpA when you SELECT INTO #temp.
May I request you to please add some more context around your answer. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.