Sunday, February 19, 2012

How can I generate xsd files from existing tables?

I would like to generate xml schema files for my data model for later use with testing tools such as ndbunit. I realize that Visual Studio datasets can be used to do this, however, Visual Studio does not automatically determine table realtionships. I do not want to manually specify these relationships. I also do not have the luxury of using TeamServer for DB professionals. The Database Diagrams feature of SQL Server Management Studio seems capable of determining the table relationships on its own. However, I don't see any way to simply export a databse diagram to an xml schema definition. I realize I could write code to do this myself using the nice APIs under the Microsoft.Sqlserver.management and System.xml namespace, but I'm trying to avoid doing this. Is there a way to do this with SQL Server Management Studio?

Would something like this work for you? It's not technically a "right-click" operation, but it does generate the schema:

SELECT *
FROM Customers
FOR XML RAW('Customer'), XMLSCHEMA('urn:example.com')
-

<xsd:schema targetNamespace="urn:example.com"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:sqltypes=
"http://schemas.microsoft.com/sqlserver/2004/sqltypes"
elementFormDefault="qualified">
<xsd:import namespace=
"http://schemas.microsoft.com/sqlserver/2004/sqltypes" />
<xsd:element name="Customer">
...
</xsd:element>
</xsd:schema>
<Customer xmlns="urn:example.com" CustomerID="ALFKI" CompanyName="Alfreds Futterkiste" ContactName="Maria Anders" ContactTitle="Sales Representative" Address="Obere Str. 57" City="Berlin" PostalCode="12209" Country="Germany" Phone="030-0074321" Fax="030-0076545" />
...

|||Thanks for the suggestion. This will work fine for my needs!|||

I should be a little clearer. If you want just the schema for the table, select something that returns all nulls or an empty set, but make sure you use the XMLSCHEMA option. You can find more about that in Books Online - past this in the "URL" bar of BOL:

ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.en/udb9/html/04b35145-1cca-45f4-9eb7-990abf2e647d.htm

Buck

|||When using the XMLSCHEMA option, I cannot seem to get the generated schema to contain foreign key constraints. I looked over the MSDN documentation, but I have not found any specific options related to this. Is this a limitation or am I simply missing some parameters that will cause the contraints to be included?|||You're not missing anything - it definitely won't do that. I would suggest you live.com search for a "database documenter" script (there are tons out there) and add the XMLSCHEMA to the end of one of those. That should give you a database design in an XML document.

No comments:

Post a Comment