我需要列出Pivot格式的表列表的所有DISTINCT
列名称。我需要列标题是实际的列名,以便我可以看到哪些表缺少列。
在下面的示例中,使用前两个表格,ChnlngAssess_PTR
应将问题尝试列(第6列)设为空白。
table_name RespID LTID UserID ProjectID QuestionAttempt QType Question
----------------------------------------------------------------------------------------
ARTWBT_PTR RespID LTID UserID ProjectID QuestionAttempt QType Question
ChlngAssess_PTR RespID LTID UserID ProjectID QType Question
答案 0 :(得分:2)
将AdventureWorksDW2012替换为您的数据库名称,如果您想限制表格,请在WHERE
t.TABLE_NAME
子句
IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL DROP TABLE #tempTable
SELECT
t.TABLE_NAME,
c.COLUMN_NAME
INTO #tempTable
FROM
AdventureWorksDW2012.INFORMATION_SCHEMA.TABLES t
inner join
AdventureWorksDW2012.INFORMATION_SCHEMA.COLUMNS c on c.TABLE_NAME = t.TABLE_NAME
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
+ QUOTENAME(COLUMN_NAME)
FROM (SELECT DISTINCT COLUMN_NAME FROM #tempTable) AS COLUMN_NAME
SET @DynamicPivotQuery =
N'SELECT TABLE_NAME, ' + @ColumnName + '
FROM #tempTable
PIVOT(Max(COLUMN_NAME)
FOR COLUMN_NAME IN (' + @ColumnName + ')) AS PVTTable'
EXEC sp_executesql @DynamicPivotQuery
答案 1 :(得分:0)
这将在数据库的所有表中找到所有字段名称。
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
ORDER BY schema_name, table_name;