Sunday, April 13, 2014

FOR XML Clause: get XDR or XSD Schema only Without XML Data


Previous 2 posts, we learned about XMLDATA and XMLSCHEMA directive of the FOR XML clause.
These 2 directives returns the XDR(XML-Data Reduced) and XSD(XML Schema Definition) schema along with the XML data. In this post, we will learn how to get only the XDR or XSD schema without XML data.
--This query returns the XML-Data Schema only without the XML data
SELECT custid, contactname
FROM   Sales.Customers 
WHERE  1 <> 1 -- this condition always evaluated to false, thus empty set is returned.
FOR    XML RAW
     , XMLDATA;
Result: notice that only the XDR schema is returned.
 
<Schema name="Schema1" xmlns="urn:schemas-microsoft-com:xml-data" xmlns:dt="urn:schemas-microsoft-com:datatypes">
  <ElementType name="row" content="empty" model="closed">
    <AttributeType name="custid" dt:type="i4" />
    <AttributeType name="contactname" dt:type="string" />
    <attribute type="custid" />
    <attribute type="contactname" />
  </ElementType>
</Schema>
--This query returns the XSD Schema only without the XML data.
SELECT  custid, contactname, fax
FROM    Sales.Customers
WHERE   1 <> 1 -- this condition always evaluated to false, thus empty set is returned.
FOR XML RAW('Customer')
      , ELEMENTS XSINIL
      , ROOT('Customers')
      , XMLSCHEMA;
Result: Notice that only the XSD schema is returned.
<Customers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <xsd:schema targetNamespace="urn:schemas-microsoft-com:sql:SqlRowSet1" 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="Customer">
      <xsd:complexType>
        <xsd:sequence>
          <xsd:element name="custid" type="sqltypes:int" nillable="1" />
          <xsd:element name="contactname" nillable="1">
            <xsd:simpleType>
              <xsd:restriction base="sqltypes:nvarchar" sqltypes:localeId="1033" sqltypes:sqlCompareOptions="IgnoreCase IgnoreKanaType IgnoreWidth" sqltypes:sqlSortId="52">
                <xsd:maxLength value="30" />
              </xsd:restriction>
            </xsd:simpleType>
          </xsd:element>
          <xsd:element name="fax" nillable="1">
            <xsd:simpleType>
              <xsd:restriction base="sqltypes:nvarchar" sqltypes:localeId="1033" sqltypes:sqlCompareOptions="IgnoreCase IgnoreKanaType IgnoreWidth" sqltypes:sqlSortId="52">
                <xsd:maxLength value="24" />
              </xsd:restriction>
            </xsd:simpleType>
          </xsd:element>
        </xsd:sequence>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
</Customers>

Reference:
MS 70-461 Training Kit.

No comments:

Post a Comment