I found this tsql query that shows the xml schema of a table and it works very well.
SELECT * FROM TableA
FOR XML AUTO, XMLSCHEMA
I am now attempting to show the relationship between tables via this query. I am not sure if this is possible. I have mocked up several test tables and I have not had any luck. Basically, I am creating a one to many relationship between tableA and tableB, then in the xml schema it would show tableA as a parent and tableB would be a child within the schema.
This is what I have been running. :
SELECT * FROM TableA,
dbo.TableB
FOR XML AUTO, XMLSCHEMA
Here is an example xml schema file that I am getting from the above query.
<xsd:schema targetNamespace="urn:schemas-microsoft-com:sql:SqlRowSet7" xmlns:schema="urn:schemas-microsoft-com:sql:SqlRowSet7" 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" schemaLocation="http://schemas.microsoft.com/sqlserver/2004/sqltypes/sqltypes.xsd" />
<xsd:element name="TableA">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="columnA" type="sqltypes:int" />
<xsd:element name="columnB">
<xsd:simpleType>
<xsd:restriction base="sqltypes:varchar" sqltypes:localeId="1033" sqltypes:sqlCompareOptions="BinarySort">
<xsd:maxLength value="50" />
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element ref="schema:dbo.tylersTestTable2" minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="TableB">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="columnA" type="sqltypes:int" />
<xsd:element name="columnB">
<xsd:simpleType>
<xsd:restriction base="sqltypes:varchar" sqltypes:localeId="1033" sqltypes:sqlCompareOptions="BinarySort">
<xsd:maxLength value="50" />
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="fkToTableA" type="sqltypes:int" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
As you can see it is displaying the tables as equal levels within the schema and not really displaying a parent child relationship.
I am kind of at a loss here as I am no dba, but I have to do this for a ton of tables and I don’t want to have to write them all by hand.
Any ideas on this one?
Tables in TSQL do not have true parent-child relationships. Each table is at the same level and foreign key relationships may cause constraints on data in one or both tables. Logically, one table may be a parent and one a child, but in no way does that mean they are a physical hierarchy. You may be able to generate XML like you’re asking for with a modeling tool like ERwin that interprets the physical model into a logical one but TSQL really only sees the physical model.