Get structure of temp table (like generate sql script) and clear temp table for current instance
Asked Answered
T

7

91

How do I get structure of temp table then delete temp table. Is there a sp_helptext for temp tables? Finally is it possible to then delete temp table in same session or query window?

Example:

select *
into #myTempTable  -- creates a new temp table
from tMyTable  -- some table in your database

tempdb..sp_help #myTempTable

Reference.

Tapes answered 23/1, 2012 at 18:7 Comment(2)
Using CTEs in Sql Server it seems to drop the temp table automatically: technet.microsoft.com/en-us/library/…Tapes
need to do this for redshiftStupor
T
149

You need to use quotes around the temp table name and you can delete the temp table directly after using drop table ....

select *
into #myTempTable  -- creates a new temp table
from tMyTable  -- some table in your database

exec tempdb..sp_help '#myTempTable'

drop table #myTempTable
Trussing answered 24/1, 2012 at 6:50 Comment(2)
Might I add that this solution is a bit overkill on system resources. If just the table structure is needed, add a "WHERE 0=1" at the end of the select.Jett
Is there a reason this sp takes so long?Traprock
M
38

I needed to be able to recreate a temp table in a script, so I used this code generate the columns part of the CREATE TABLE statement:

SELECT char(9) + '[' + c.column_name + '] ' + c.data_type 
   + CASE 
        WHEN c.data_type IN ('decimal')
            THEN isnull('(' + convert(varchar, c.numeric_precision) + ', ' + convert(varchar, c.numeric_scale) + ')', '') 
        WHEN c.data_type IN ('varchar', 'nvarchar', 'char', 'nchar')
            THEN isnull('(' 
                + CASE WHEN c.character_maximum_length = -1
                    THEN 'max'
                    ELSE convert(varchar, c.character_maximum_length) 
                  END + ')', '')
        ELSE '' END
   + CASE WHEN c.IS_NULLABLE = 'YES' THEN ' NULL' ELSE '' END
   + ','
FROM tempdb.INFORMATION_SCHEMA.COLUMNS c 
WHERE TABLE_NAME LIKE '#myTempTable%' 
ORDER BY c.ordinal_position

I didn't test for all sql datatypes, but this worked for int, float, datetime, money, and bit.

Also - ApexSQL Complete (free) has a nice feature where you can export grid results into an Insert Into statement. I used this to load this created temp table in my script. ApexSQL Copy Results As Insert into statement

Mousterian answered 21/2, 2018 at 20:48 Comment(5)
Good solution, if you'd add the max size you'd make it a great script!Calamanco
Also want to ORDER BY the ordinal_position so the column defs come out in the same sequence as the original.Length
@Eli, good suggestion. I edited the script for max size of character typesMousterian
@PaulEvans, right. I edited the script to order the columns correctlyMousterian
@Tapes may I suggest this be marked be marked as the accepted answer for it directly provides the requested output.Warnock
A
14

As long as I know there is no SP_HelpText for tables. Try this:

Select * From tempdb.sys.columns Where object_id=OBJECT_ID('tempdb.dbo.#myTempTable');
Amend answered 24/1, 2012 at 5:41 Comment(1)
There certainly is sp_HelpText for tables, including temp tables. Please try SELECT X INTO #TEMP FROM (VALUES (CAST (2 AS INT))) T (X); EXEC tempdb..sp_help '#TEMP'; Knobkerrie
P
8

To Get structure of temp table

enter image description here

Many of us will use common methods like Keyboard Shortcut – ‘Alt+F1‘ or will use ‘SP_HELPTEXT‘ Command (so many other methods are also there) to view the Structure of Physical Table. As we all know, Viewing the Structure of Temp Table is not as common as Viewing the Structure of Physical Table. we are going to see, how to view the Structure of Temp Table easily in SQL Server. The below mentioning methods are applicable at both Azure SQL DB and On-Premises.

Demo SQL Script

IF OBJECT_ID('TempDB..#TempTable') IS NOT NULL
    DROP TABLE #TempTable;

SELECT 1 AS ID,'Arul' AS Names
INTO
#TempTable;

SELECT * FROM #TempTable;

METHOD 1 – Using SP_HELP

EXEC TempDB..SP_HELP #TempTable;

enter image description here

Note-

In the Table Structure, the Table Name shows something like ‘#TempTable__________________________________________________________________________________________________________0000000004CB’. Actually, the total length of each and every Temp Table name will be 128 . To handle the Same Temp Table name in Multiple Sessions differently, SQL Server will automatically add some underscores in between and alphanumeric’s at end.

METHOD 2 – Using SP_COLUMNS

EXEC TempDB..SP_COLUMNS '#TempTable';

enter image description here

METHOD 3 – Using System Tables like INFORMATION_SCHEMA.COLUMNS, SYS.COLUMNS, SYS.TABLES

SELECT * FROM TempDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME IN (
SELECT NAME FROM TempDB.SYS.TABLES WHERE OBJECT_ID=OBJECT_ID('TempDB.dbo.#TempTable')
);
GO

SELECT * FROM TempDB.SYS.COLUMNS WHERE OBJECT_ID=OBJECT_ID('TempDB.dbo.#TempTable');
GO

SELECT * FROM TempDB.SYS.TABLES WHERE OBJECT_ID=OBJECT_ID('TempDB.dbo.#TempTable');
GO

enter image description here

To Clear temp table for current instance

IF OBJECT_ID('TempDB..#TempTable') IS NOT NULL
    DROP TABLE #TempTable;
Pyotr answered 18/1, 2020 at 7:22 Comment(0)
B
6
Select * From tempdb.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE '#yourtemp%'
Boigie answered 30/5, 2016 at 6:0 Comment(0)
W
3

exec sp_columns table_name;

example

exec sp_columns employees;

Winifield answered 16/9, 2013 at 5:33 Comment(0)
S
1

So, this helped me. It created the Table columns.

Select Column_Name + ' [' + DATA_TYPE + ']' + 
case when Data_Type in ('numeric', 'varchar', 'char')
    then '(' +
        case
            when DATA_TYPE = 'numeric' then CAST(numeric_precision as varchar(3)) + ',' + CAST(numeric_scale as varchar(3))
            when DATA_TYPE = 'varchar' then CAST(CHARACTER_MAXIMUM_LENGTH as varchar(3))
            when DATA_TYPE = 'char' then CAST(CHARACTER_MAXIMUM_LENGTH as varchar(3))
        end
         + ')'
    else ''
end
+ ','
, * 
From tempdb.INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME LIKE '#MEHTEMPTABLE%'

All I then needed to do was copy these items into a Table Declaration

Declare @MyTable Table
(
--All columns here
)

That would've resolved my issue, but I was pressed for time

Suicidal answered 19/4, 2019 at 8:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.