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.
Using the DROP TABLE command on a temporary table, as with any table, will delete the table and remove all data. In an SQL server, when you create a temporary table, you need to use the # in front of the name of the table when dropping it, as this indicates the temporary table.
You can also do it by copy your temp table's data to new table and get script of the new table. You can also use SSMS Tools pack just go ssmstoolspack.com/Features? f=9 and see how it is working!
To create a Global Temporary Table, add the “##” symbol before the table name. Global Temporary Tables are visible to all connections and Dropped when the last connection referencing the table is closed. Global Table Name must have an Unique Table Name.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With