0

我正在尝试编写一个 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;
4

2 回答 2

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'
于 2013-05-08T06:27:00.730 回答
0

这将解决您的问题

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS 

您可以访问所有表和视图信息

于 2013-05-08T06:29:37.790 回答