从SQL查询中获取XML输出

时间:2013-12-29 05:19:41

标签: sql-server sql-server-2008

我正在编写SQL查询以获得如下输出。我没有使用数据库中的任何表。 用于获取所需输出的查询

<Property ID="0" Name="Color" NumOfItems="11">
    <Item ID="0" Name="D"/>
    <Item ID="1" Name="E"/>
    <Item ID="2" Name="F"/>
    <Item ID="3" Name="G"/>
    <Item ID="4" Name="H"/>
    <Item ID="5" Name="I"/>
    <Item ID="6" Name="J"/>
    <Item ID="7" Name="K"/>
    <Item ID="8" Name="L"/>
    <Item ID="9" Name="M"/>
    <Item ID="10" Name="N"/>
  </Property>

我试过这个

      SELECT 
   (
     SELECT '0' AS 'Item/@ID','D' AS 'Item/@Name'  FOR XML PATH(''), TYPE ),
     (SELECT '1' AS 'Item/@ID','E' AS 'Item/@Name'  FOR XML PATH(''), TYPE ),
     (SELECT '2' AS 'Item/@ID','F' AS 'Item/@Name'  FOR XML PATH(''), TYPE ),
     (SELECT '3' AS 'Item/@ID','G' AS 'Item/@Name'  FOR XML PATH(''), TYPE ),
     (SELECT '4' AS 'Item/@ID','H' AS 'Item/@Name'  FOR XML PATH(''), TYPE ),
     (SELECT '5' AS 'Item/@ID','I' AS 'Item/@Name'  FOR XML PATH(''), TYPE ),
     (SELECT '6' AS 'Item/@ID','J' AS 'Item/@Name'  FOR XML PATH(''), TYPE ),
     (SELECT '7' AS 'Item/@ID','K' AS 'Item/@Name'  FOR XML PATH(''), TYPE ),
     (SELECT '8' AS 'Item/@ID','L' AS 'Item/@Name'  FOR XML PATH(''), TYPE ),
     (SELECT '9' AS 'Item/@ID','M' AS 'Item/@Name'  FOR XML PATH(''), TYPE ),
     (SELECT '10' AS 'Item/@ID','N' AS 'Item/@Name'  FOR XML PATH(''), TYPE )
 FOR XML PATH(''),
 ROOT('Property'),TYPE

2 个答案:

答案 0 :(得分:2)

  

我没有使用数据库中的任何表

好吧SELECT它......

SELECT CAST ('<Property ID="0" Name="Color" NumOfItems="11">
    <Item ID="0" Name="D"/>
    <Item ID="1" Name="E"/>
    <Item ID="2" Name="F"/>
    <Item ID="3" Name="G"/>
    <Item ID="4" Name="H"/>
    <Item ID="5" Name="I"/>
    <Item ID="6" Name="J"/>
    <Item ID="7" Name="K"/>
    <Item ID="8" Name="L"/>
    <Item ID="9" Name="M"/>
    <Item ID="10" Name="N"/>
  </Property>' AS XML)

答案 1 :(得分:0)

1)

SELECT  *
FROM    (VALUES (0, 'Color', 11)) Property(ID, Name, NumOfItems)
JOIN    (VALUES (0,0,'D'), (0,1,'E'), (0,2,'F')) Item(PropertyID,ID,Name) 
ON      Property.ID = Item.PropertyID
FOR XML AUTO

输出:

<Property ID="0" Name="Color" NumOfItems="11">
  <Item PropertyID="0" ID="0" Name="D" />
  <Item PropertyID="0" ID="1" Name="E" />
  <Item PropertyID="0" ID="2" Name="F" />
</Property>

2)

SELECT  *,
        (SELECT * FROM (VALUES (0,'D'), (1, 'E'), (2, 'F')) MamboJambo("@ID", "@Name") FOR XML PATH('Item'),TYPE) 
FROM    (VALUES (0,'Color',11)) CocoJambo("@ID", "@Name", "@NumOfItems") 
FOR XML PATH('Property')

3)

SELECT  CONVERT(XML, N'<Property ID="0" Name="Color" NumOfItems="11">
    <Item ID="0" Name="D"/>
    <Item ID="1" Name="E"/>
    <Item ID="2" Name="F"/>
  </Property>').query(N'
    for $x in (/Property)
    return 
        <Property ID="{$x/@ID}" Name="{$x/@Name}" NumOfItems="{$x/@NumOfItems}" >
        {for $y in ($x/Item) return $y}
        </Property>
');