You must create a temporary, global table with a variable-dependent name. For example:

DECLARE @TableName nvarchar(max) = 'TempTableName' CREATE TABLE ##@TableName([id] int) 

Creates a table named ##@TableName , not with ##TempTableName

How to create such a global temporary table?

  • one
    Try using the stored procedure sp_executesql , I don’t know if it is really performing the DDL, but suddenly ... - Mike
  • one
    @Mike, sp_executesql executes any queries for which the user has enough rights, including DDL. I advise you to issue your comment as an answer. - Sergey Rufanov

1 answer 1

You must use the stored procedure sp_executesql , which can execute a query dynamically assembled as a string:

 DECLARE @TableName nvarchar(max) = 'TempTableName'; DECLARE @Sql NVARCHAR(max) = 'create table ##' + @TableName +'([id] int)'; EXECUTE sp_executesql @Sql