Technical Article

Recreate a temporary table from TempDB

,

you might have used select X,Y,Z,* into #Foo from ....., and Once you have created the temporary table , you can then run this script to pull that table back out if you need to reuse it

Use tempdb;
GO

Declare @TableName varchar(100)= 'MyTempTable'

Declare @Output varchar(max)

 Select @Output = 

Coalesce(@Output, CHAR(13)) + 
'[' + COLUMN_NAME + '] '  + c.DATA_TYPE + Case When Character_Maximum_Length is null then '' 
  else '('+Cast(Character_MAXIMUM_LENGTH as varchar)+')' end 
+ Case When IS_NULLABLE = 'YES' 
then ' NULL' 
Else ' NOT NULL' end + ','   
+ CHAR(13)

FROM Information_Schema.Columns c
Where TABLE_CATALOG ='Tempdb'
And TABLE_NAME like '#' +@Tablename +'%'
Order by c.ORDINAL_POSITION asc

Print 'Create Table #'+@TableName+' (' + Left(@Output,Len(@Output)-2)+CHAR(13)+')'

Rate

3.14 (7)

You rated this post out of 5. Change rating

Share

Share

Rate

3.14 (7)

You rated this post out of 5. Change rating