for xml subqueries

In Transact-SQL, an expression subquery is a parenthesized subquery. It has a single column, the value of which is the expression subquery result, and must return a single row. You can use an expression subquery almost anywhere you can use an expression. For more information about subqueries, see the Transact-SQL® User’s Guide.

The for xml subqueries feature allows you to use any subquery containing a for xml clause as an expression subquery.

Syntax

 subquery ::= select [all | distinct ] select_list
     (select select_list
     [from table_reference [, table_reference]... ]
     [where search_conditions]
     [group by aggregate_free_expression [aggregate_free_expression]...]
     [having search_conditions]
     [for_xml_clause])
 for_xml_clause:: = See “for xml schema and for xml all” on page 64
 table_reference::= table_view_name |ANSI_join | derived_table
 table_view_name::= See SELECT in Vol. 2, “Commands, in the      “Reference Manual”
 ANSI_join::= See SELECT in Vol. 2, “Commands,” in the “Reference      Manual”
 derived_table::= (subquery) as table_name

Description

Exceptions

Examples

Example 1 A for xml subquery returns the XML document as a string value, which you can assign to a string column or variable, or pass as an argument to a stored procedure or built-in function. For example:

declare @doc varchar(16384)
set @doc = (select * from systypes for xml returns varchar(16384))
select @doc
--------------

Example 2 To pass the result of a for xml subquery as a string argument, enter:

select xmlextract('//row[usertype = 18]',
     (select * from systypes for xml))
------------

Example 3 To specify a for xml subquery as a value in insert or update:

create table docs_xml(id integer, doc_xml text)
insert into docs_xml
   select(1, (select * from systypes for xml)
--------

update docs_xml
set doc_xml = (select * from sysobjects for xml)
where id = 1
------------