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:
DECLARE @viewname VARCHAR(50);
SET @viewname ='tableorviewname';
SELECT c.name + ' '+ t.name +
case t.name
WHEN 'varchar' THEN '('+CAST(c.max_length AS VARCHAR(3) )+'),'
ELSE ','
end
FROM sys.columns c
INNER JOIN sys.types AS t ON c.system_type_id = t.system_type_id
WHERE object_id = (SELECT object_id from sys.objects where name = @viewname)
ORDER BY c.column_id
EDIT: TEMP TABLES:
temp tables are slightly different, for instance this works in sql 2008 for a temp table named #tv_source
DECLARE @viewortablename VARCHAR(50);
SET @viewortablename ='tempdb..#tv_source';
SELECT c.name + ' '+ t.name +
case t.name
WHEN 'varchar' THEN '('+CAST(c.max_length AS VARCHAR(3) )+'),'
ELSE ','
end
FROM tempdb.sys.columns c
INNER JOIN sys.types AS t ON c.system_type_id = t.system_type_id
WHERE object_id = object_id(@viewortablename)
ORDER BY c.column_id
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.
SELECT
', ['+ac.name+'] '+Type_Name(User_type_id)+
CASE WHEN Type_Name(User_type_id) = 'Decimal'
THEN +'('+CONVERT(Varchar(4),ac.Precision)+','+CONVERT(Varchar(4),ac.Scale)+')'
WHEN Type_Name(User_type_id) IN
('tinyint','smallint','int','real','money','float','numeric','smallmoney','DateTime')
THEN ''
ELSE +'('+CONVERT(Varchar(4),ac.Max_Length)+')'
END AS TableColumn
FROM Tempdb.sys.all_columns AS ac
INNER JOIN Tempdb.Sys.SysObjects AS so
ON so.ID = ac.Object_ID
WHERE 1 = 1
AND so.Name = '##YourTempTableGoesHere'
...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?
CREATE FUNCTION [dbo].[fnDiscoverColumns]
( @PObjectName NVARCHAR(300) )
RETURNS @Data TABLE ( ColumnList NVARCHAR(350) )
AS
BEGIN
DECLARE @PObjectID TABLE ( [object_id] INT )
INSERT @PObjectID ( [object_id] )
SELECT [object_id] FROM sys.objects AS O WHERE O.name = @PObjectName AND O.type = 'U'
DECLARE @PObjectDetails TABLE ( [RowNo] INT,[ColumnName] NVARCHAR(300),[XType] INT,[DataType] NVARCHAR(100),[system_type_id] INT,[user_type_id] INT,[MaxLength] NVARCHAR(5),[Precision] INT,[Scale] INT,[ColumnList] NVARCHAR(300) )
INSERT @PObjectDetails ( [RowNo],[ColumnName],[XType],[DataType],[system_type_id],[user_type_id],[MaxLength],[Precision],[Scale],[ColumnList] )
SELECT DISTINCT
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS 'RowNo',
C.name AS 'ColumnName',
T.xtype AS 'XType',
UPPER(T.name) AS 'DataType',
C.system_type_id,
C.user_type_id,
CASE WHEN C.max_length < 0 THEN 'MAX' ELSE CAST(C.max_length AS VARCHAR) END AS 'MaxLength',
C.precision AS 'Precision',
C.scale AS 'Scale',
CASE
WHEN [XType] IN (34,35,36,40,48,52,56,58,59,60,61,62,98,99,104,122,127,189,240,241) THEN QUOTENAME(C.name) +' '+ UPPER(T.name) +','
WHEN [XType] IN (106,108) THEN QUOTENAME(C.name) +' '+ UPPER(T.name) +'('+ CAST([Precision] AS VARCHAR) +','+ CAST(C.scale AS VARCHAR) +'),'
WHEN [XType] IN (41,42,43,165,167,173,175,231,239) THEN QUOTENAME(C.name) +' '+ UPPER(T.name) +'('+ CASE WHEN C.max_length < 0 THEN 'MAX' WHEN C.max_length > 1 THEN CAST(C.max_length / 2 AS VARCHAR) ELSE CAST(C.max_length AS VARCHAR) END +'),' ELSE NULL END AS 'ColumnList'
FROM sys.all_columns AS C
JOIN systypes AS T ON C.system_type_id = T.xusertype
WHERE C.object_id = (SELECT * FROM @PObjectID) --373576369
--Return column names and data types
INSERT @Data
SELECT 'CREATE TABLE #ColumnsList ('
INSERT @Data
SELECT
CASE WHEN C.RowNo = (SELECT MAX(RowNo) FROM @PObjectDetails) THEN LEFT(C.ColumnList, ABS(LEN(C.ColumnList + ',') - 2)) ELSE C.ColumnList END AS 'GeneratedColumns'
FROM @PObjectDetails AS C
INSERT @Data
SELECT ')'
RETURN
END
GO
Once committed to the database, run it like this:
SELECT * FROM [dbo].[fnDiscoverColumns] ('ExecutionLogStorage') --name of table
This should give you an output like this:
CREATE TABLE #ColumnsList (
[LogEntryId] BIGINT,
[InstanceName] NVARCHAR(38),
[ReportID] UNIQUEIDENTIFIER,
[UserName] NVARCHAR(260),
[ExecutionId] NVARCHAR(64),
[RequestType] TINYINT,
[Format] NVARCHAR(26),
[Parameters] NTEXT,
[ReportAction] TINYINT,
[TimeStart] DATETIME,
[TimeEnd] DATETIME,
[TimeDataRetrieval] INT,
[TimeProcessing] INT,
[TimeRendering] INT,
[Source] TINYINT,
[Status] NVARCHAR(40),
[ByteCount] BIGINT,
[RowCount] BIGINT,
[AdditionalInfo] XML
)