0

Is there a way to create a dynamic temp table. Below sql code is declaring a variable @tic. I am planning to insert contents from table1 to temp table #df. So instead of giving directly as #df, I am passing as a variable. But below is code is not successful. Can anyone help me here?

declare @tic as varchar(100) = 'df'

select *
into '#' + @tic from (
select * from [dbo].[table1])

select * from #df
3
  • Why should I "tag my RDBMS"? - please add a tag to specify whether you're using mysql, postgresql, sql-server, oracle or db2 - or something else entirely. Commented Apr 17, 2021 at 7:22
  • 2
    I don't believe it's possible, you would need Dynamic Sql however the temp table would only be available within the scope of the d-sql. You'd be better off using a permanent table and including an identifier column to keep different session data unique. Commented Apr 17, 2021 at 9:08
  • 2
    What problem are you trying to solve here? Single-# temp tables are only visible to the current connection, even if multiple concurrent connections make their own #df temp table, so you don't need to make the name dynamic. Commented Apr 17, 2021 at 9:24

1 Answer 1

1

Is there a way? Well, I think of the answer as "yes and no and maybe".

As far as I know, there is no way to do this using a local temporary table. As Stu explains in the comment, you would need dynamic SQL to define the table name and then the table would not be visible in the outer scope, because it is a local temporary table.

The "yes" is because one type of temporary table are global temporary tables. These are tables that persist across different scopes. And they are defined using ## instead of # as the prefix. So this works:

declare @tic as varchar(100) = 'df'

declare @sql nvarchar(max);
set @sql = 'select * into ##' + @tic + ' from table1';

select @sql;

exec sp_executesql @sql;

select * from ##df;

(Here is a db<>fiddle.)

The "maybe" is because I'm quite skeptical that you really need this. Dynamic table names are rarely useful in SQL systems, precisely because they depend on dynamic SQL. Introducing dynamic names into SQL (whether columns or tables) is dangerous, both because of the danger of SQL injection and also because it can introduce hard-to-debug syntax errors.

If you are trying to solve a real problem, there might be alternative approaches that are better suited to SQL Server.

Sign up to request clarification or add additional context in comments.

1 Comment

I did consider this but if it needs to be a global table, ie usable by all sessions, it would be much easier to just create a normal table in tempdb . As you say, understanding the problem being solved would help.

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.