如果您只需要表的 xml 架构,请使用以下命令查询它们:
select top 0 * FROM daTable FOR XML AUTO,XMLSCHEMA
如果您需要表名和列来创建数据库的表示以及表的连接方式,您可以使用以下内容:
SELECT
s.name as '@Schema'
,t.name as '@Name'
,t.object_id as '@Id'
,(
SELECT c.name as '@Name'
,c.column_id as '@Id'
,IIF(ic.object_id IS NOT NULL,1,0) as '@IsPrimaryKey'
,fkc.referenced_object_id as '@ColumnReferencesTableId'
,fkc.referenced_column_id as '@ColumnReferencesTableColumnId'
FROM sys.columns as c
LEFT OUTER JOIN sys.index_columns as ic
ON c.object_id = ic.object_id
AND c.column_id = ic.column_id
AND ic.index_id = 1
LEFT OUTER JOIN sys.foreign_key_columns as fkc
ON c.object_id = fkc.parent_object_id
AND c.column_id = fkc.parent_column_id
WHERE c.object_id = t.object_id
FOR XML PATH ('Column'),TYPE
)
FROM sys.schemas as s
INNER JOIN sys.tables as t
ON s.schema_id = t.schema_id
FOR XML PATH('Table'),ROOT('Tables')
让您的应用程序使用 ColumnReferencesTableId 和 ColumnReferencesTableColumnId 来获取表关系。如果您更喜欢写出它们的名称,您还可以进一步加入引用的列和表,但我认为它们的 ID 就足够了。