Chapter 6: Developing Database Applications with ADO.NET 219 Here you can see again how the connection object has been passed in at the top of the routine. DataAdapter, DataSet, and CommandBuilder objects are then created. The DataSet is then filled inside the Try-Catch loop. The next statement shows retrieving the last row in the SpecialOffer table into a DataRow object. The Description field of the DataRow is then set with a new value, which changes the Table.Rows.RowState property for this row to reflect Modified. The next statement calls the DataAdapter’s Update method. The Update method determines the appropriate command to execute from the value of the RowState property; in this case, it will call the UpdateCommand of the DataAdapter to resolve the changed row back to the data source. Delete Using the CommandBuilder The next example shows deleting a record from the database. Private Sub DataSetDeleteSql(cn As SqlConnection) ' Create the dataadapter, and commandbuilder Dim sqlDA As SqlDataAdapter = New SqlDataAdapter( _ "SELECT * FROM Sales.SpecialOffer", cn) Dim ds = New DataSet() Dim sqlCB = New SqlCommandBuilder(sqlDA) Try ' Populate the dataset sqlDA.Fill(ds, "SpecialOffer") ' Mark the record in the datatable for deletion Dim sqlDR = ds.Tables("SpecialOffer").Rows( _ ds.Tables("SpecialOffer").Rows.Count - 1) sqlDR.Delete() ' Delete the record from the database table sqlDA.Update(ds, "SpecialOffer") Catch e As Exception MsgBox(e.Message) End Try End Sub Again you can see the connection object passed into the routine, and the DataAdapter, DataSet, and CommandBuilder objects being created. Then the DataSet is filled in the Try-Catch loop. The next statement retrieves the last row from the SpecialOffer DataTable into a DataRow object. Then the DataRow’s Delete method is called to delete the row from the DataTable SpecialOffer. In reality, this does not physically delete the row from the DataTable but instead sets the Table.Rows.RowState property to Deleted. Next, when the DataAdapter’s 220 Microsoft SQL Server 2005 Developer’s Guide Update method is called, the DeleteCommand of the DataAdapter will execute and delete the record from the database. In contrast, if you call the DataTable’s Remove or RemoveAt method, the row will be physically removed from the DataTable in the DataSet. If you use the Remove or RemoveAt method and then call the Update method, the row in the data source will not be deleted, because the DataAdapter’s Update method determines what action to take from the Table. Rows.RowState property and all of the remaining rows in the DataTable have a RowState of Unmodified; therefore, no action will take place at the data source. Summary In this chapter, you got a view of how to develop SQL Server database applications using Visual Basic and ADO.NET. You were introduced to the different ADO.NET namespaces and given an overall understanding of the functions of the different classes that compose the ADO.NET architecture. 221 CHAPTER 7 Developing with XML IN THIS CHAPTER The XML Data Type XQuery Support XML Data Type Methods XML Indexes Using the For XML Clause OPENXML XML Bulk Load Native HTTP SOAP Access Copyright © 2006 by The McGraw-Hill Companies. Click here for terms of use. 222 Microsoft SQL Server 2005 Developer’s Guide X ML (Extensible Markup Language) is the lingua franca of computer languages. XML’s flexible text-based structure enables it to be used for an incredibly wide array of network tasks, including for data/document transfer, for Web page rendering, and even as a transport for Web services via SOAP (Simple Object Access Protocol). Microsoft first added basic support for XML to SQL Server 2000, by adding the FOR XML clause as part of the SELECT statement and the OpenXML function. The FOR XML clause allowed a SELECT statement to return an XML document containing the results, while the OpenXML function created a rowset over XML contained in one or more columns. To this basic level, Microsoft’s SQL XML Web release for SQL Server 2000 added support for UpdateGrams, Templates, and BulkLoad to XML Views, as well as stored procedure access via Web services and SOAP. However, SQL Server 2000’s support for XML had some limitations. The XML data needed to be stored in a SQL Server database using either the Text or Image data type. Once it was stored, there was little that SQL Server could do with it. SQL Server 2000 was unable to natively query the stored XML. SQL Server had no checks on the validity of the data, and in order to query the XML documents, you essentially needed to extract and parse each document on a one-at-a-time, per-row basis. SQL Server 2005 builds on this starting point by adding support for many new XML features. First, SQL Server 2005 provides a new level of unified storage for XML and relational data by adding a new XML data type. SQL Server 2005’s native XML data type provides support for both native XML queries using XQuery as well as strong data typing by associating the XML data type to an XSD (Extensible Schema Definition). The XML support is tightly integrated with the SQL Server 2005 relational database engine. SQL Server 2005 provides support for triggers on XML, replication of XML data, and bulk load of XML data, as well as enhanced support for data access via SOAP. In this chapter you’ll see how to develop applications that make use of SQL Server 2005’s native XML support. The XML Data Type The XML data type can be used as a column in a table or a variable or parameter in a stored procedure. It can be used to store both typed and untyped data. If the data stored in an XML column has no XSD schema, then it is considered untyped. If there is an associated XSD schema, then SQL Server 2005 will check all data inserted into the data type against the schema to make sure that the data store complies with the schema definition. In all cases, SQL Server 2005 checks the data that is stored in the XML data type to ensure that it is well formed, although partial documents Chapter 7: Developing with XML 223 are allowed. If you attempt to insert invalid data into the XML data type, SQL Server 2005 will raise an error and the data will not be stored. The XML data type can accept a maximum of 2GB of data, and its on-disk storage structure is like the varbinary(max) data type. The following listing illustrates creating a simple table that uses the new XML data type: CREATE TABLE MyXMLDocs (DocID INT PRIMARY KEY, MyXmlDoc XML) Here the MyXmlDoc column uses the XML data type to specify that the column will store XML data. You can populate an XML column in the same way that you do other data types, using either T-SQL or ADO.NET client applications. The following example shows how you can store a value in an XML column using a T-SQL INSERT statement: INSERT INTO MyXmlDocs Values (1,'<MyXMLDoc> <DocumentID>1</DocumentID> <DocumentText>Text</DocumentText> </MyXMLDoc>') Data Validation Using an XSD Schema The native XML data type checks to ensure that any data that’s stored in an XML variable or column is a valid XML document. On its own, it doesn’t check any more than that. However, Microsoft designed the XML data type to be able to support more sophisticated document validation using an XSD schema. When an XSD schema is defined for an XML data type column, the SQL Server engine will check to make sure that all of the data stored in the XML column complies with the definition that’s supplied by the XSD schema. Creating the XSD Schema The following listing shows a sample XSD schema for the simple XML document that was used in the preceding example: <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="MyXMLDocSchema" xmlns="MyXMLDocSchema"> <xs:element name="MyXMLDoc"> <xs:complexType> 224 Microsoft SQL Server 2005 Developer’s Guide <xs:sequence> <xs:element name="DocumentID" type="xs:int" /> <xs:element name="DocumentBody" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> This XSD schema uses the namespace of MyXMLDocSchema and defines an XML document that has a complex element named MyXMLDoc. The MyXMLDoc complex element contains two simple elements. The first simple element must be named DocumentID, and a second simple element is named DocumentBody. The DocumentID element must contain an integer, while the DocumentBody element must contain XML string-type data. To create a strongly typed XML column or variable, you first need to register the XSD schema with SQL Server using the CREATE XML SCHEMA COLLECTION statement. This registers the schema in the SQL Server database. After the XSD schema is registered, it can be used by an XML data type. You can see an example of using the CREATE XML SCHEMA COLLECTION statement in the following listing: CREATE XML SCHEMA COLLECTION MyXMLDocSchema AS N'<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://MyXMLDocSchema"> <xs:element name="MyXMLDoc"> <xs:complexType> <xs:sequence> <xs:element name="DocumentID" type="xs:int" /> <xs:element name="DocumentBody" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>' The CREATE XML SCHEMA COLLECTION statement takes a single argument that names the collection. Next, after the AS clause it expects a valid XSD schema enclosed in single quotes. If the schema is not valid, an error will be issued when the statement is executed. The CREATE XML SCHEMA COLLECTION statement is database specific, and the schema that is registered can be accessed only in the database for which the schema is registered. Chapter 7: Developing with XML 225 NOTE The CREATE XML SCHEMA COLLECTION statement requires that the XSD schema be passed as a variable. It cannot read the schema in from a disk file. Once you’ve registered the XML schema with a SQL Server 2005 database, you can go ahead and associate XML variables and columns with that schema. You associate the XML data type with the schema when it is first created. Providing the XML data type with a schema allows SQL Server to check that any XML data that is placed in that data type will adhere to the definition provided by the associated schema. The following example illustrates how you can create a table that uses the MyXMLDocSchema that was created earlier: CREATE TABLE MyXMLDocs (DocID INT PRIMARY KEY, MyXmlDoc XML(MyXMLDocSchema)) NOTE If you previously created the MyXMLDocs table in your example database, you would need to drop the table before running this code. As in the earlier example, the MyXMLDocs table is created using the CREATE TABLE statement. However, in this example the MyXMLDoc column is created using an argument that specifies that name of the registered XSD schema definition named MyXMLDocSchema. There’s no change to the basic way that you insert data into the typed XML column. However, once the DocumentBody column has been typed, all of the data that’s stored there must comply with XSD schema definition. The following listing shows how you can use an INSERT statement to add data to the MyXMLDoc column: INSERT INTO MyXMLDocs (DocID, MyXMLDoc)Values (1,'<MyXMLDoc xmlns="http://MyXMLDocSchema"> <DocumentID>1</DocumentID> <DocumentBody>"My text"</DocumentBody> </MyXMLDoc>') The value for the DocID column is a standard integer data type of 1. The XML data that’s inserted into the MyXMLDoc column must comply with the MyXMLDoc Schema. The XML document must reference the associated XML namespace http:// MyXMLDocSchema. It must also possess a complex element named MyXMLDoc, 226 Microsoft SQL Server 2005 Developer’s Guide which in turn contains the DocumentID and DocumentBody elements. The SQL Server engine will raise an error if you attempt to insert any other XML document into the MyXMLDocs column. For example, the code in the following listing attempts to insert a row that contains XML data that doesn’t comply with the MyXMLDocSchema: INSERT INTO MyXmlDocs (DocID, MyXMLDoc) Values (3,'<root>empty</root>') Because the data does not conform to the associated XSD schema, SQL Server will return an error message like the one shown in the following listing: Msg 6913, Level 16, State 1, Line 1 XML Validation: Declaration not found for element 'root'. Location: /*:root[1] NOTE As you might expect from their dependent relationship, if you assign a schema to a column in a table, that table must be altered or dropped before that schema definition can be updated. Retrieving a Registered XML Schema Once you import a schema using CREATE XML SCHEMA COLLECTION, the schema components are stored by SQL Server. The stored schema can be listed by querying the sys.xml_schema_collections system view, as you can see in the following example: SELECT * FROM sys.xml_schema_collections The sys.xml_schema_collections view is database specific. This statement will return a result set showing all of the registered schemas in a database like the one that follows: xml_collection_id schema_id principal_id name 1 4 NULL sys 65537 1 NULL MyXMLDocSchema (2 row(s) affected) Chapter 7: Developing with XML 227 You can also use the new XML_SCHEMA_NAMESPACE function to retrieve the XML schema. The following listing illustrates retrieving the MyXMLDocSchema schema. SELECT XML_SCHEMA_NAMESPACE(N'dbo',N'MyXMLDocSchema') This statement will return a result set showing the registered schema, as you can see here: <xsd:schema xmlns:xsd=http://www.w3.org/2001/XMLSchema xmlns:t="http://MyXMLDocSchema" targetNamespace="http://MyXMLDocSchema" elementFormDefault="qualified"> <xsd:element name="MyXMLDoc"> <xsd:complexType> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="DocumentID" type="xsd:int" /> <xsd:element name="DocumentBody" type="xsd:string" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:element> </xsd:schema> NOTE Executing this script with SQL Server Management Studio’s Query Editor returns a grid with a single column containing a hyperlink. Clicking the hyperlink displays the XSD in the XML Editor, which displays the result that you can see in the preceding listing. XQuery Support In the preceding section you saw how XQuery is used in the new XML data type’s methods. XQuery is based on the XPath language created by the W3C (www.w3c.org) for querying XML data. XQuery extends the XPath language by adding the ability to update data as well as support for better iteration and sorting of results. T-SQL supports a subset of the XQuery language that is used for querying the XML data type. One of the coolest things about SQL Server’s XQuery support is the tight integration it has with the relational engine. XQuery is closely integrated with T-SQL, and the XML 228 Microsoft SQL Server 2005 Developer’s Guide queries are not restricted to the contents of a single XML row but instead can cross multiple rows exactly like relational queries, without the need to extract and parse the XML for each row. A description of the XQuery language is beyond the scope of this book, but this section will show you some of the basics for getting started using XQuery to query SQL Server’s XML data type. Querying Element Data XQuery is a flexible query language that’s well suited to querying XML documents that have a hierarchical structure. In this section you’ll learn about the basics of using XQuery in conjunction with T-SQL to query the data store in SQL Server 2005’s XML data type. Querying Multiple Elements XQuery can return the result from one XML node or multiple nodes. The following example illustrates returning all of the subelements and their values: DECLARE @x xml SET @x = '<Myroot><Element1>One</Element1><Element2>Two</Element2></Myroot>' SELECT @x.query('/Myroot') Here the new variable @x of the XML data type is populated using the SET statement and has the following structure: <Myroot> <Element1>One</Element1> <Element2>Two</Element2> </Myroot> The XQuery is executed using the XML data type’s Query method. (More information about the XML data type methods is presented in the following section.) The XQuery itself basically requests all of the nodes that are children of the /Myroot node. You can see the results in the following listing: <Myroot><Element1>One</Element1><Element2>Two</Element2></Myroot> (1 row(s) affected) . complex element named MyXMLDoc, 226 Microsoft SQL Server 2005 Developer’s Guide which in turn contains the DocumentID and DocumentBody elements. The SQL Server engine will raise an error if. document on a one-at-a-time, per-row basis. SQL Server 2005 builds on this starting point by adding support for many new XML features. First, SQL Server 2005 provides a new level of unified storage. Schema Definition). The XML support is tightly integrated with the SQL Server 2005 relational database engine. SQL Server 2005 provides support for triggers on XML, replication of XML data,