简体   繁体   中英

How do I extract a database schema using T-SQL?

I'd like to extract an XML schema from a database (a "database schema") using a T-SQL query in SQL management studio, rather than C# code. The schema should include all tables in the database.

I can get a single table using the following:

DECLARE @schema xml
SET @schema = (SELECT * FROM Student FOR XML AUTO, ELEMENTS, XMLSCHEMA('StudentSchema'))
select @schema

But how do I combine the remaining tables? All of my tables are related in some way.

See also this question , which discusses how to do it in code.

You could alway use sp_msforeachtable and dynamic sql:

exec sp_MSforeachtable '
DECLARE @schema xml
SET @schema = (SELECT * FROM ? FOR XML AUTO, ELEMENTS, XMLSCHEMA(''?Schema''))
select @schema
'

You may have a naming issue with the schema name since I think you will have dbo. or schema prefix to the table name.

You mean Information Schema Views (Transact-SQL)

SELECT * FROM INFORMATION_SCHEMA.COLUMNS
FOR XML AUTO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM