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

前端 未结 7 2096
粉色の甜心
粉色の甜心 2021-01-30 19:56

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

7条回答
  •  爱一瞬间的悲伤
    2021-01-30 20:32

    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.

提交回复
热议问题