Thus far, we've looked at how data can be retrieved from SQL Server in XML format, but we haven't talked about how to update SQL Server data using XML. Updategrams provide an XML-based method of updating data in a SQL Server database. They are basically templates with special attributes and elements that allow you to specify the data you want to update and how you want to update it. An updategram contains a before image and an after image of the data you want to change. You submit updategrams to SQL Server in much the same way as you submit templates. All the execution mechanisms available with templates work equally well with updategrams. You can POST updategrams via HTTP, save updategrams to files and execute them via URLs, and execute updategrams directly via ADO and OLE DB.
How They Work
Updategrams are based on the xml-updategram namespace. You reference this namespace via the xmlns:updg qualifier. Each updategram contains at least one sync element. This sync element contains the data changes you wish to make in the form of before and after elements. The before element contains the before image of the data you wish to change. Normally, it will also contain a primary key or candidate key reference so that SQL Server will be able to locate the row you wish to change. Note that only one row can be selected for update by the before element. If the elements and attributes included in the before element identify more than one row, you'll receive an error message.
For row deletions, an updategram will have a before image but no after image. For insertions, it will have an after image but no before image. And, of course, for updates, an updategram will have both a before image and an after image. Listing 18.58 provides an example.
Listing 18.58
<?xml version="1.0"?> <employeeupdate xmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> <updg:sync> <updg:before> <Employees EmployeeID="4"/> </updg:before> <updg:after> <Employees City="Scotts Valley" Region="CA"/> </updg:after> </updg:sync> </employeeupdate>
In this example, we change the City and Region columns for Employee 4 in the Northwind Employees table. The EmployeeID attribute in the before element identifies the row to change, and the City and Region attributes in the after element identify which columns to change and what values to assign them.
Each batch of updates within a sync element is considered a transaction. Either all the updates in the sync element succeed or none of them do. You can include multiple sync elements to break updates into multiple transactions.
Mapping Data
Of course, in sending data to the server for updates, deletions, and insertions via XML, we need a means of linking values in the XML document to columns in the target database table. SQL Server sports two facilities for doing this: default mapping and mapping schemas.
Default Mapping
Naturally, the easiest way to map data in an updategram to columns in the target table is to use the default mapping (also known as intrinsic mapping). With default mapping, a before or after element's top-level tag is assumed to refer to the target database table, and each subelement or attribute it contains refers to a column of the same name in the table.
Here's an example that shows how to map the OrderID column in the Orders table:
<Orders OrderID="10248"/>
This example maps XML attributes to table columns. You could also map subelements to table columns, like this:
<Orders> <OrderID>10248</OrderID> </Orders>
You need not select either attribute-centric or element-centric mapping. You can freely mix them within a given before or after element, as shown below:
<Orders OrderID="10248"> <ShipCity>Reims</ShipCity> </Orders>
Use the four-digit hexadecimal UCS-2 code for characters in table names that are illegal in XML elements (e.g., spaces). For example, to reference the Northwind Order Details table, do this:
<Order_x0020_Details OrderID="10248"/>
Mapping Schemas
You can also use XDR and XSD mapping schemas to map data in an updategram to tables and columns in a database. You use a sync's updg:mapping-schema attribute to specify the mapping schema for an updategram. Listing 18.59 shows an example that specifies an updategram for the Orders table.
Listing 18.59
<?xml version="1.0"?> <orderupdate xmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> <updg:sync updg:mapping-schema="OrderSchema.xml"> <updg:before> <Order OID="10248"/> </updg:before> <updg:after> <Order City="Reims"/> </updg:after> </updg:sync> </orderupdate>
Listing 18.60 shows its XDR mapping schema.
Listing 18.60
<?xml version="1.0"?> <Schema xmlns="urn:schemas-microsoft-com:xml-data" xmlns:sql="urn:schemas-microsoft-com:xml-sql"> <ElementType name="Order" sql:relation="Orders"> <AttributeType name="OID"/> <AttributeType name="City"/> <attribute type="OID" sql:field="OrderID"/> <attribute type="City" sql:field="ShipCity"/> </ElementType> </Schema>
Listing 18.61 shows its XSD mapping schema.
Listing 18.61
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:sql="urn:schemas-microsoft-com:mapping-schema"> <xsd:element name="Order" sql:relation="Orders" > <xsd:complexType> <xsd:attribute name="OID" sql:field="OrderId" type="xsd:integer" /> <xsd:attribute name="City" sql:field="ShipCity" type="xsd:string" /> </xsd:complexType> </xsd:element> </xsd:schema>
As you can see, a mapping schema maps the layout of the XML document to the Northwind Orders table. See the Mapping Schemas section earlier in the chapter for more information on building XML mapping schemas.
NULLs
It's common to represent missing or inapplicable data as NULL in a database. To represent or retrieve NULL data in an updategram, you use the sync element's nullvalue attribute to specify a placeholder for NULL. This placeholder is then used everywhere in the updategram that you need to specify a NULL value, as demonstrated in Listing 18.62.
Listing 18.62
<?xml version="1.0"?> <employeeupdate xmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> <updg:sync updg:nullvalue="NONE"> <updg:before> <Orders OrderID="10248"/> </updg:before> <updg:after> <Orders ShipCity="Reims" ShipRegion="NONE" ShipName="NONE"/> </updg:after> </updg:sync> </employeeupdate>
As you can see, we define a placeholder for NULL named NONE. We then use this placeholder to assign a NULL value to the ShipRegion and ShipName columns.
Parameters
Curiously, parameters work a little differently with updategrams than with templates. Rather than using at (@) symbols to denote updategram parameters, you use dollar ($) symbols, as shown in Listing 18.63.
Listing 18.63
<?xml version="1.0"?> <orderupdate xmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> <updg:header> <updg:param name="OrderID"/> <updg:param name="ShipCity"/> </updg:header> <updg:sync> <updg:before> <Orders OrderID="$OrderID"/> </updg:before> <updg:after> <Orders ShipCity="$ShipCity"/> </updg:after> </updg:sync> </orderupdate>
This nuance has interesting implications for passing currency values as parameters. To pass a currency parameter value to a table column (e.g., the Freight column in the Orders table), you must map the data using a mapping schema.
NULL Parameters
In order to pass a parameter with a NULL value to an updategram, include the nullvalue placeholder attribute in the updategram's header element. You can then pass this placeholder value into the updategram to signify a NULL parameter value. This is similar to the way you specify a NULL value for a column in an updategram, the difference being that you specify nullvalue within the sync element for column values but within the header element for parameters. Listing 18.64 shows an example.
Listing 18.64
<?xml version="1.0"?> <orderupdate xmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> <updg:header nullvalue="NONE"> <updg:param name="OrderID"/> <updg:param name="ShipCity"/> </updg:header> <updg:sync> <updg:before> <Orders OrderID="$OrderID"/> </updg:before> <updg:after> <Orders ShipCity="$ShipCity"/> </updg:after> </updg:sync> </orderupdate>
This updategram accepts two parameters. Passing a value of NONE will cause the ShipCity column to be set to NULL for the specified order.
Note that we don't include the xml-updategram (updg:) qualifier when specifying the nullvalue placeholder for parameters in the updategram's header.
Multiple Rows
I mentioned earlier that each before element can identify at most one row. This means that to update multiple rows, you must include an element for each row you wish to change.
The id Attribute
When you specify multiple subelements within your before and after elements, SQL Server requires that you provide a means of matching each before element with its corresponding after element. One way to do this is through the id attribute. The id attribute allows you to specify a unique string value that you can use to match a before element with an after element. Listing 18.65 gives an example.
Listing 18.65
<?xml version="1.0"?> <orderupdate xmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> <updg:sync> <updg:before> <Orders updg:id="ID1" OrderID="10248"/> <Orders updg:id="ID2" OrderID="10249"/> </updg:before> <updg:after> <Orders updg:id="ID2" ShipCity="Munster"/> <Orders updg:id="ID1" ShipCity="Reims"/> </updg:after> </updg:sync> </orderupdate>
Here, we use the updg:id attribute to match up subelements in the before and after elements. Even though these subelements are specified out of sequence, SQL Server is able to apply the updates to the correct rows.
Multiple before and after Elements
Another way to do this is to specify multiple before and after elements rather than multiple subelements. For each row you want to change, you specify a separate before/after element pair, as demonstrated in Listing 18.66.
Listing 18.66
<?xml version="1.0"?> <orderupdate xmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> <updg:sync> <updg:before> <Orders OrderID="10248"/> </updg:before> <updg:after> <Orders ShipCity="Reims"/> </updg:after> <updg:before> <Orders OrderID="10249"/> </updg:before> <updg:after> <Orders ShipCity="Munster"/> </updg:after> </updg:sync> </orderupdate>
As you can see, this updategram updates two rows. It includes a separate before/after element pair for each update.
Results
The result returned to a client application that executes an updategram is normally an XML document containing the empty root element specified in the updategram. For example, we would expect to see this result returned by the orderupdate updategram:
<?xml version="1.0"?> <orderupdate xmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> </orderupdate>
Any errors that occur during updategram execution are returned as <?MSSQLError> elements within the updategram's root element.
Identity Column Values
In real applications, you often need to be able to retrieve an identity value that's generated by SQL Server for one table and insert it into another. This is especially true when you need to insert data into a table whose primary key is an identity column and a table that references this primary key via a foreign key constraint. Take the example of inserting orders in the Northwind Orders and Order Details tables. As its name suggests, Order Details stores detail information for the orders in the Orders table. Part of Order Details' primary key is the Orders table's OrderID column. When we insert a new row into the Orders table, we need to be able to retrieve that value and insert it into the Order Details table.
From Transact-SQL, we'd usually handle this situation with an INSTEAD OF insert trigger or a stored procedure. To handle it with an updategram, we use the at-identity attribute. Similarly to the id attribute, at-identity serves as a placeholder—everywhere we use its value in the updategram, SQL Server supplies the identity value for the corresponding table. (Each table can have just one identity column.) Listing 18.67 shows an example.
Listing 18.67
<?xml version="1.0"?> <orderinsert xmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> <updg:sync> <updg:before> </updg:before> <updg:after> <Orders updg:at-identity="ID" ShipCity="Reims"/> <Order_x0020_Details OrderID="ID" ProductID="11" UnitPrice="$16.00" Quantity="12"/> <Order_x0020_Details OrderID="ID" ProductID="42" UnitPrice="$9.80" Quantity="10"/> </updg:after> </updg:sync> </orderinsert>
Here, we use the string “ID” to signify the identity column in the Orders table. Once the string is assigned, we can use it in the insertions for the Order Details table.
In addition to being able to use an identity column value elsewhere in an updategram, it's quite likely that you'll want to be able to return it to the client. To do this, use the after element's returnid attribute and specify the at-identity placeholder as its value, as shown in Listing 18.68.
Listing 18.68
<?xml version="1.0"?> <orderinsert xmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> <updg:sync> <updg:before> </updg:before> <updg:after updg:returnid="ID"> <Orders updg:at-identity="ID" ShipCity="Reims"/> <Order_x0020_Details OrderID="ID" ProductID="11" UnitPrice="$16.00" Quantity="12"/> <Order_x0020_Details OrderID="ID" ProductID="42" UnitPrice="$9.80" Quantity="10"/> </updg:after> </updg:sync> </orderinsert>
Executing this updategram will return an XML document that looks like this:
<?xml version="1.0"?> <orderinsert xmlns:updg= "urn:schemas-microsoft-com:xml-updategram"> <returnid> <ID>10248</ID> </returnid> </orderinsert>
Globally Unique Identifiers
It's not unusual to see Globally Unique Identifiers (GUIDs) used as key values across a partitioned view or other distributed system. (These are stored in columns of type uniqueidentifier.) Normally, you use the Transact-SQL NEWID() function to generate new uniqueidentifiers. The updategram equivalent of NEWID() is the guid attribute. You can specify the guid attribute to generate a GUID for use elsewhere in a sync element. As with id, nullvalue, and the other attributes presented in this section, the guid attribute establishes a placeholder that you can then supply to other elements and attributes in the updategram in order to use the generated GUID. Listing 18.69 presents an example.
Listing 18.69
<orderinsert> xmlns:updg="urn:schemas-microsoft-com:xml-updategram"> <updg:sync> <updg:before> </updg:before> <updg:after> <Orders updg:guid="GUID"> <OrderID>GUID</OrderID> <ShipCity>Reims</ShipCity> </Orders> <Order_x0020_Details OrderID="GUID" ProductID="11" UnitPrice="$16.00" Quantity="12"/> <Order_x0020_Details OrderID="GUID" ProductID="42" UnitPrice="$9.80" Quantity="10"/> </updg:after> </updg:sync> </orderinsert>