Udostępnij za pośrednictwem


Using RAW Mode

RAW mode transforms each row in the query result set into an XML element that has the generic identifier <row>, or the optionally provided element name. By default, each column value in the rowset that is not NULL is mapped to an attribute of the <row> element. If the ELEMENTS directive is added to the FOR XML clause, each column value is mapped to a subelement of the <row> element. Together with the ELEMENTS directive, you can optionally specify the XSINIL option to map NULL column values in the result set to an element that has the attribute, xsi:nil="true".

The BINARY BASE64 option must be specified in the FOR XML clause to return the binary data in base64-encoded format. In RAW mode, retrieving binary data without specifying the BINARY BASE64 option will result in an error.

You can request a schema for the resulting XML. Specifying the XMLDATA option returns an in-line XDR schema. Specifying the XMLSCHEMA option returns an in-line XSD schema. The schema appears at the start of the data. In the result, the schema namespace reference is repeated for every top-level element.

Examples

The queries in the following examples show how FOR XML RAW mode is used with various options. Many of these queries are specified against the bicycle manufacturing instructions XML documents that are stored in the Instructions column of the ProductModel table. For more information about the XML instructions, see xml Data Type Representation in the AdventureWorks Database.

A. Retrieving product model information as XML

The following query returns product model information. RAW mode is specified in the FOR XML clause.

USE AdventureWorks;
GO
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID=122 or ProductModelID=119
FOR XML RAW;
GO

This is the partial result:

<row ProductModelID="122" Name="All-Purpose Bike Stand" />

<row ProductModelID="119" Name="Bike Wash" />

You can retrieve element-centric XML by specifying the ELEMENTS directive.

USE AdventureWorks;
GO
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID=122 or ProductModelID=119
FOR XML RAW, ELEMENTS;
GO

This is the result:

<row>
  <ProductModelID>122</ProductModelID>
  <Name>All-Purpose Bike Stand</Name>
</row>
<row>
  <ProductModelID>119</ProductModelID>
  <Name>Bike Wash</Name>
</row>

You can optionally specify the TYPE directive to retrieve the results as xml type. The TYPE directive does not change the content of the results. Only the data type of the results is affected.

USE AdventureWorks;
GO
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID=122 or ProductModelID=119
FOR XML RAW, TYPE ;
GO

B. Specifying XSINIL with the ELEMENTS directive to generate elements for null column values

The following query specifies the ELEMENTS directive to generate element-centric XML from the query result.

USE AdventureWorks;
GO
SELECT ProductID, Name, Color
FROM Production.Product
FOR XML RAW, ELEMENTS;
GO

This is the partial result.

<row>
  <ProductID>1</ProductID>
  <Name>Adjustable Race</Name>
</row>
...
<row>
  <ProductID>317</ProductID>
  <Name>LL Crankarm</Name>
  <Color>Black</Color>
</row>

Because the Color column has null values for some products, the resulting XML will not generate the corresponding <Color> element. By adding the XSINIL directive with ELEMENTS, you can generate the <Color> element even for NULL color values in the result set.

USE AdventureWorks;
GO
SELECT ProductID, Name, Color
FROM Production.Product
FOR XML RAW, ELEMENTS XSINIL

This is the partial result:

<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ProductID>1</ProductID>
  <Name>Adjustable Race</Name>
  <Color xsi:nil="true" />
</row>
...
<row>
  <ProductID>317</ProductID>
  <Name>LL Crankarm</Name>
  <Color>Black</Color>
</row>

C. Requesting schemas for the result using the XMLDATA and XMLSCHEMA options

The following query returns the XML-DATA schema that describes the document structure.

USE AdventureWorks;
GO
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID=122 or ProductModelID=119
FOR XML RAW, XMLDATA
GO

This is the result:

<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="ProductModelID" dt:type="i4" />
    <AttributeType name="Name" dt:type="string" />
    <attribute type="ProductModelID" />
    <attribute type="Name" />
  </ElementType>
</Schema>
<row xmlns="x-schema:#Schema1" ProductModelID="122" Name="All-Purpose Bike Stand" />
<row xmlns="x-schema:#Schema1" ProductModelID="119" Name="Bike Wash" />

Note

The <Schema> is declared as a namespace. To avoid namespace collisions when multiple XML-Data schemas are requested in different FOR XML queries, the namespace identifier, Schema1 in this example, changes with every query execution. The namespace identifier is made up of Scheman where n is an integer.

By specifying the XMLSCHEMA option, you can request the XSD schema for the result.

USE AdventureWorks;
GO
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID=122 or ProductModelID=119
FOR XML RAW, XMLSCHEMA
GO

This is the result:

<xsd:schema targetNamespace="urn:schemas-microsoft-com:sql:SqlRowSet1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:sqltypes="https://schemas.microsoft.com/sqlserver/2004/sqltypes" elementFormDefault="qualified">
  <xsd:import namespace="https://schemas.microsoft.com/sqlserver/2004/sqltypes" schemaLocation="https://schemas.microsoft.com/sqlserver/2004/sqltypes/sqltypes.xsd" />
  <xsd:element name="row">
    <xsd:complexType>
      <xsd:attribute name="ProductModelID" type="sqltypes:int" use="required" />
      <xsd:attribute name="Name" use="required">
        <xsd:simpleType sqltypes:sqlTypeAlias="[AdventureWorks].[dbo].[Name]">
          <xsd:restriction base="sqltypes:nvarchar" sqltypes:localeId="1033" sqltypes:sqlCompareOptions="IgnoreCase IgnoreKanaType IgnoreWidth" sqltypes:sqlSortId="52">
            <xsd:maxLength value="50" />
          </xsd:restriction>
        </xsd:simpleType>
      </xsd:attribute>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>
<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" ProductModelID="122" Name="All-Purpose Bike Stand" />
<row xmlns="urn:schemas-microsoft-com:sql:SqlRowSet1" ProductModelID="119" Name="Bike Wash" />

You can specify the target namespace URI as an optional argument to XMLSCHEMA in FOR XML. This returns the specified target namespace in the schema. This target namespace remains the same every time you execute the query. For example, the following modified version of the previous query includes the namespace URI, 'urn:example.com', as an argument.

USE AdventureWorks;
GO
SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID=122 or ProductModelID=119
FOR XML RAW, XMLSCHEMA ('urn:example.com')
GO

This is the result:

<xsd:schema targetNamespace="urn:example.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:sqltypes="https://schemas.microsoft.com/sqlserver/2004/sqltypes" elementFormDefault="qualified">
  <xsd:import namespace="https://schemas.microsoft.com/sqlserver/2004/sqltypes" schemaLocation="https://schemas.microsoft.com/sqlserver/2004/sqltypes/sqltypes.xsd" />
  <xsd:element name="row">
    <xsd:complexType>
      <xsd:attribute name="ProductModelID" type="sqltypes:int" use="required" />
      <xsd:attribute name="Name" use="required">
        <xsd:simpleType sqltypes:sqlTypeAlias="[AdventureWorks].[dbo].[Name]">
          <xsd:restriction base="sqltypes:nvarchar" sqltypes:localeId="1033" sqltypes:sqlCompareOptions="IgnoreCase IgnoreKanaType IgnoreWidth" sqltypes:sqlSortId="52">
            <xsd:maxLength value="50" />
          </xsd:restriction>
        </xsd:simpleType>
      </xsd:attribute>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>
<row xmlns="urn:example.com" ProductModelID="122" Name="All-Purpose Bike Stand" />
<row xmlns="urn:example.com" ProductModelID="119" Name="Bike Wash" />

D. Retrieving binary data

The following query returns the product photo stored in a varbinary(max) type column. The BINARY BASE64 option is specified in the query to return the binary data in base64-encoded format.

USE AdventureWorks
GO
SELECT ProductPhotoID, ThumbNailPhoto
FROM Production.ProductPhoto
WHERE ProductPhotoID=1
FOR XML RAW, BINARY BASE64 ;
GO

This is the result:

<row ProductModelID="1" ThumbNailPhoto="base64 encoded binary data"/>

E. Renaming the <row> element

For each row in the result set, the RAW mode generates an element <row>. You can optionally specify another name for this element by specifying an optional argument to the RAW mode, as shown in this query. The query returns a <ProductModel> element for each row in the rowset.

SELECT ProductModelID, Name 
FROM Production.ProductModel
WHERE ProductModelID=122
FOR XML RAW ('ProductModel'), ELEMENTS
GO

This is the result. Because the ELEMENTS directive is added in the query, the result is element-centric.

<ProductModel>
  <ProductModelID>122</ProductModelID>
  <Name>All-Purpose Bike Stand</Name>
</ProductModel> 

F. Specifying a root element for the XML generated by FOR XML

By specifying the ROOT option in the FOR XML query, you can request a single, top-level element for the resulting XML, as shown in this query. The argument specified for the ROOT directive provides the root element name.

USE AdventureWorks;
GO
SELECT ProductModelID, Name 
FROM Production.ProductModel
WHERE ProductModelID=122 or ProductModelID=119 or ProductModelID=115
FOR XML RAW, ROOT('MyRoot')
go

This is the result:

<MyRoot>
  <row ProductModelID="122" Name="All-Purpose Bike Stand" />
  <row ProductModelID="119" Name="Bike Wash" />
  <row ProductModelID="115" Name="Cable Lock" />
</MyRoot>

G. Querying xml type columns

The following query includes columns of xml type. The query retrieves product model ID, name, and manufacturing steps at the first location from the Instructions column of the xml type.

USE AdventureWorks;
GO
SELECT ProductModelID, Name,
   Instructions.query('
declare namespace MI="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions"
   /MI:root/MI:Location[1]/MI:step
') 
FROM Production.ProductModel
FOR XML RAW ('ProductModelData')
GO

The following is the result. Note that the table stores manufacturing instructions for only some product models. The manufacturing steps are returned as subelements of the <ProductModelData> element in the result.

<ProductModelData ProductModelID="5" Name="HL Mountain Frame" />
<ProductModelData ProductModelID="6" Name="HL Road Frame" />
<ProductModelData ProductModelID="7" Name="HL Touring Frame">
    <MI:step> ... </MI:step>
    <MI:step> ... </MI:step>
 </ProductModelData>

If the query specifies a column name for the XML returned by the XQuery, as specified in the following SELECT statement, the manufacturing steps are wrapped in the element that has the specified name.

USE AdventureWorks;
GO
SELECT ProductModelID, Name,
   Instructions.query('
declare namespace MI="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions"
   /MI:root/MI:Location[1]/MI:step
') as ManuSteps
FROM Production.ProductModel
FOR XML RAW ('ProductModelData')
go

This is the result:

<ProductModelData ProductModelID="5" Name="HL Mountain Frame" />
<ProductModelData ProductModelID="6" Name="HL Road Frame" />
<ProductModelData ProductModelID="7" Name="HL Touring Frame">
  <ManuSteps>
    <MI:step ... </MI:step>
    <MI:step ... </MI:step>
  </ManuSteps>
</ProductModelData>

The following query specifies the ELEMENTS directive. Therefore, the result returned is element-centric. The XSINIL option specified with the ELEMENTS directive returns the <ManuSteps> elements, even if the corresponding column in the rowset is NULL.

USE AdventureWorks;
GO
SELECT ProductModelID, Name,
   Instructions.query('
declare namespace MI="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions"
   /MI:root/MI:Location[1]/MI:step
') as ManuSteps
FROM Production.ProductModel
FOR XML RAW ('ProductModelData'), root('MyRoot'), ELEMENTS XSINIL
go

This is the result:

<MyRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   ...
  <ProductModelData>
    <ProductModelID>6</ProductModelID>
    <Name>HL Road Frame</Name>
    <ManuSteps xsi:nil="true" />
  </ProductModelData>
  <ProductModelData>
    <ProductModelID>7</ProductModelID>
    <Name>HL Touring Frame</Name>
    <ManuSteps>
      <MI:step ... </MI:step>
      <MI:step ...</MI:step>
       ...
    </ManuSteps>
  </ProductModelData>
</MyRoot>

H. Adding namespaces using WITH XMLNAMESPACES

For examples, see Adding Namespaces Using WITH XMLNAMESPACES.

See Also

Reference

Using AUTO Mode
Using EXPLICIT Mode
Constructing XML Using FOR XML

Concepts

Adding Namespaces Using WITH XMLNAMESPACES
Using PATH Mode

Other Resources

SELECT (Transact-SQL)

Help and Information

Getting SQL Server 2005 Assistance