I create temp tables quite often in SQL and I am looking into a way to generate the column names and datatypes automatically for the table definition so I don't have to look them all up everytime.
For example I run:
SELECT CustomerID
ClientID,
FirstName
LastName
INTO #Test
From dbo.Customer
To initially setup the temp table with the appropriate columns and data I need. Once I get that all done, I then go back in and take out the INTO statement and write the following:
CREATE TABLE #Test
(
...
...
);
I want to find a way to auto generate the column names and datatypes from the initial creation of the temp table. Right now, since I am initially inserting into an automatically created temp table, I use this:
EXEC tempdb..sp_help '#Test';
This gives me everything I need without having to look all the column datatypes up, but I wanted to know if there was a way to just auto gen the column names off of something like this. So the auto gen would generate:
CustomerID int,
ClientID int,
FirstName varchar(50),
LastName varchar(50)
This would allow me to just copy and paste this into my create table statement.
this might give you a start:
EDIT: TEMP TABLES:
temp tables are slightly different, for instance this works in sql 2008 for a temp table named #tv_source
NOTES: this gives a comma separated list, but did NOT attempt to remove that last comma, it gives only a list, which you would likely want to put on a string and manipulate, etc. then use as a dynamic sql or somthing. Still, it should give you a start on what you wish to do.
NOTE for to others, sql 2000 would not display the lengths properly for instance on a varchar(45), it would just list the varchar part and I did not attempt to rework that for this question.
...I've created a function that can output the list of columns and datatypes, if the object is a table, if that is something that would be useful for you?
Once committed to the database, run it like this:
This should give you an output like this: