Have you ever needed to store the results of a complex query in a temp table? How did you go about working out what the definition for that temp table should be, the columns and their data types?
It can be a bit of a pain, not to mention time consuming to have to go figuring out what all datatypes of the base tables are.
I got fed up with all that hunting around as well so as a quick blog I thought I’d share a little script that will take your query in a variable and print out a temp table definition for its result set.
It uses the fantastically useful DMV, sys.dm_exec_describe_first_result_set.
Just assign the value of @Query with the query that you’re interested in and @TempTableName with the name of the temp table that you want to create.
SET NOCOUNT ON DECLARE @Query VARCHAR(MAX) = 'select * from sys.databases' DECLARE @TempTableName VARCHAR(128) = '#temptable' DECLARE @ColumnList VARCHAR(MAX) SELECT @ColumnList = STUFF((SELECT ',' + name + ' ' + system_type_name + ' ' + CASE is_nullable WHEN 0 THEN 'NOT NULL' ELSE 'NULL' END + CHAR(10) FROM sys.dm_exec_describe_first_result_set(@Query, NULL, 0) FOR XML PATH('')) ,1,1,'') PRINT 'CREATE TABLE ' + @TempTableName + '(' PRINT @ColumnList PRINT(')')
I hope you find it useful 🙂