Let us learn about XML Document in TSQL using XSD by Jacob Sebastian.
XML Schema Collections
Because of the ‘eXtensible’ nature of XML (eXtensible Markup Language), often there is a requirement to restrict and validate the content of an XML document to a pre-defined structure and values. XSD (XML Schema Definition Language) is the W3C recommended language for describing and validating XML documents. SQL Server implements XSD as XML Schema Collections.
An XML Schema Collection can be used to validate an XML document stored in an XML column or variable. To understand this better, let us see an example.
XML Document
For the purpose of this example, let us create an XML Schema Collection to validate the following XML Document.
<Employee> <FirstName>Jacob</FirstName> <MiddleName>V</MiddleName> <LastName>Sebastian</LastName> </Employee> |
Validation Rules
Here are the validation rules we are trying to implement.
- The root element should be named ‘Employee’
- The root element should have three child elements, named ‘FirstName’, ‘MiddleName’ and ‘LastName’.
- Child elements should appear exactly in the order given above.
Creating the XML Schema Collection
Here is the XML Schema collection that performs the above validations.
CREATE XML SCHEMA COLLECTION EmployeeSchema AS'<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element > <xsd:complexType> <xsd:sequence> <xsd:element /> <xsd:element /> <xsd:element /> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>' |
Validating an XML variable
The following code validates an XML document against the rules defined in the XML Schema Collection.
DECLARE @x XML(EmployeeSchema) SELECT @x = '<Employee> <FirstName>Jacob</FirstName> <MiddleName>V</MiddleName> <LastName>Sebastian</LastName> </Employee>' |
Note that the operation will succeed only if all the validation rules defined in the XML schema collection are met. For example, the following will fail because the XML document is missing the ‘MiddleName’ element.
DECLARE @x XML(EmployeeSchema) SELECT @x = '<Employee> <FirstName>Jacob</FirstName> <LastName>Sebastian</LastName> </Employee>' |
Reference: Pinal Dave (https://blog.sqlauthority.com)