Technical Article

Get Temp Table definition

,

Generate a temp table using Select * INTO #

.  Once the temp table has been created, execute this statement within the same session (tab in SSMS).  The output will have a row per line definition of the table, in column order, that can be used to explicitly declare the temp table.

I've used this in the past when I wanted to generate a temp table manually but do not want to type up the statements, or don't know what the final data types will be.  With this, I can simply identify the data I need, insert it using INTO #temp, and then execute this to generate the create statement I need.

I wrote this a few years ago so I'm sure someone can improve on it, but figured it was worth sharing anyway.  It may not work for all column data types as I've only included the ones I've needed so far.

DECLARE @TableName sysname = 'temp'; --Do not include the #

WITH PrimaryKeys AS
  (
    SELECT          TableID = ta.object_id,
                    ColumnID = col.column_id
      FROM          tempdb.sys.tables AS ta
      INNER JOIN    tempdb.sys.indexes AS ind
        ON ind.object_id = ta.object_id
      INNER JOIN    tempdb.sys.index_columns AS indcol
        ON indcol.object_id = ta.object_id
           AND  indcol.index_id = ind.index_id
      INNER JOIN    tempdb.sys.columns AS col
        ON col.object_id = ta.object_id
           AND  col.column_id = indcol.column_id
      WHERE         ind.is_primary_key = 1
  ),
     Results AS
  (
    SELECT              [Schema] = OBJECT_SCHEMA_NAME( C.object_id ),
                        [Table] = OBJECT_NAME( C.object_id ),
                        [Column] = C.name,
                        Type = T2.name + CASE
                                           WHEN T2.name LIKE '%char' THEN CASE
                                                                            WHEN C.max_length = -1 THEN '(max)'
                                                                            ELSE '(' + RTRIM( CAST(C.max_length AS CHAR(4))) + ')'
                                                                          END
                                           WHEN T2.name LIKE 'binary' THEN '(' + RTRIM( CAST(C.max_length AS CHAR(4))) + ')'
                                           WHEN T2.name IN ( 'decimal', 'numeric' ) THEN '(' + RTRIM( CAST(C.precision AS CHAR(4))) + ',' + RTRIM( CAST(C.scale AS CHAR(4))) + ')'
                                           WHEN T2.name IN ( 'datetime2' ) THEN '(' + RTRIM( CAST(C.scale AS CHAR(4))) + ')'
                                           ELSE ''
                                         END,
                        IsNullable = CASE C.is_nullable
                                       WHEN 0 THEN 'Not Null'
                                       WHEN 1 THEN 'Null'
                                     END,
                        IsPrimaryKey = CASE
                                         WHEN PK.ColumnID IS NULL THEN ''
                                         ELSE 'PRIMARY KEY'
                                       END,
                        ColumnOrder = C.column_id
      FROM              tempdb.sys.columns AS C
      INNER JOIN        tempdb.sys.types AS T2
        ON C.user_type_id = T2.user_type_id
      LEFT OUTER JOIN   PrimaryKeys AS PK
        ON C.object_id = PK.TableID
           AND  C.column_id = PK.ColumnID
      WHERE             C.object_id = OBJECT_ID( 'tempdb..#' + @TableName + '' )
  )
SELECT  SQLStatement = 'IF Object_ID(''tempdb..#' + @TableName + ''') IS NOT NULL DROP TABLE #' + @TableName + ';',
        ColumnOrder = -1
UNION ALL
SELECT  SQLStatement = 'CREATE TABLE #' + @TableName, ColumnOrder = 0
UNION ALL
SELECT  SqlStatement = CASE Results.ColumnOrder
                         WHEN 1 THEN '( '
                         ELSE ', '
                       END + QUOTENAME( Results.[Column] ) + ' ' + Results.Type + ' ' + Results.IsNullable + ' ' + Results.IsPrimaryKey,
        Results.ColumnOrder
  FROM  Results
UNION ALL
SELECT  SQLSTatement = ');', ColumnOrder = 99999
  ORDER BY  ColumnOrder
;

Rate

4.8 (5)

You rated this post out of 5. Change rating

Share

Share

Rate

4.8 (5)

You rated this post out of 5. Change rating