我正在尝试编写一个SQL查询,它将输出表和视图中的所有列。
下面的查询只返回表列,不包含视图列
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;
答案 0 :(得分:5)
试试这个(快速) -
SELECT
[object_name] = s.name + '.' + o.name
, column_name = c.name
, o.type_desc
FROM sys.objects o
JOIN sys.schemas s ON o.[schema_id] = s.[schema_id]
JOIN sys.columns c ON o.[object_id] = c.[object_id]
WHERE o.[type] IN ('U', 'V')
ORDER BY [object_name]
或尝试此操作(慢) -
SELECT
[object_name] = s.name + '.' + o.name
, column_name = c.name
FROM (
SELECT v.name, v.[object_id], v.[schema_id]
FROM sys.views v
UNION ALL
SELECT t.name, t.[object_id], t.[schema_id]
FROM sys.tables t
) o
JOIN sys.schemas s ON o.[schema_id] = s.[schema_id]
JOIN sys.columns c ON o.[object_id] = c.[object_id]
ORDER BY [object_name]
在sys.tables& sys.views:强>
ALTER VIEW sys.views AS
SELECT *
FROM sys.objects$
WHERE type = 'V'
ALTER VIEW sys.tables AS
SELECT *
FROM sys.objects$ o
LEFT JOIN sys.sysidxstats lob ON lob.id = o.object_id AND lob.indid <= 1
LEFT JOIN sys.syssingleobjrefs ds ON ds.depid = o.object_id AND ds.class = 8 AND ds.depsubid <= 1 -- SRC_INDEXTOLOBDS
LEFT JOIN sys.syssingleobjrefs rfs ON rfs.depid = o.object_id AND rfs.class = 42 AND rfs.depsubid = 0 -- SRC_OBJTOFSDS
LEFT JOIN sys.syspalvalues ts ON ts.class = 'LEOP' AND ts.value = o.lock_escalation_option
WHERE o.type = 'U'
答案 1 :(得分:0)
这将解决您的问题
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
您可以访问所有表格和视图信息