...我创建了一个可以输出列和数据类型列表的函数,如果对象是表,那对您有用吗?
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
提交到数据库后,像这样运行它:
SELECT * FROM [dbo].[fnDiscoverColumns] ('ExecutionLogStorage') --name of table
这应该会给你这样的输出:
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
)