FOR XML examples

The following examples show how the FOR XML clause can be used in a SELECT statement.

  • The following example shows how the FOR XML clause can be used in a subquery:

    SELECT XMLELEMENT( NAME root,
        (SELECT * FROM Employees FOR XML RAW) );
  • The following example shows how the FOR XML clause can be used in a query with a GROUP BY clause and aggregate function:

    SELECT Name, AVG(UnitPrice) AS Price
    FROM Products
    GROUP BY Name
    FOR XML RAW;
  • The following example shows how the FOR XML clause can be used in a view definition:

    CREATE VIEW EmployeesDepartments
    AS SELECT Surname, GivenName, DepartmentName
    FROM Employees JOIN Departments
    ON Employees.DepartmentID = Departments.DepartmentID
    FOR XML AUTO;