嵌套在SQL中生成的XML节点

时间:2014-01-21 22:33:53

标签: sql-server xml

我正在尝试生成一个类似于以下内容的XML文件。

<products>
   <product>
     <sku>12345</sku>
        <attributes>
            <attribute>
              <name>AttributeName</name>
              <row>
              <name>ProdName</name>
              <value>someProduct</value>
              </row>
            </attribute>

            <attribute>
              <name>AttributeName</name>
              <row>
              <name>color</name>
              <value>Blue</value>
              </row>
            </attribute>
        </attributes>
    </product>
</products>

使用以下SQL查询,我可以生成非常接近但需要对其进行微调的内容。

bcp "SELECT RTRIM(LTRIM(sku)) as sku, 
(SELECT 'AttributeName' AS [name],'ProdName' AS [row/name],ProdName AS [row/value] FOR XML PATH ('attribute'), Type),
(SELECT 'AttributeName' AS [name],'color' AS [row/name], color AS [row/value]      FOR XML PATH ('attribute'), Type)  
FROM Tbl_Product WHERE (SKU = 12345) FOR XML PATH ('product'), ROOT('products'),Type" queryout "..\Desktop\sample.xml" -c -T

<products>
   <product>
     <sku>12345</sku>
        <!-- need   <attributes> here -->          
            <attribute>
              <name>AttributeName</name>
              <row>
              <name>ProdName</name>
              <value>someProduct</value>
              </row>
            </attribute>

            <attribute>
              <name>AttributeName</name>
              <row>
              <name>color</name>
              <value>Blue</value>
              </row>
            </attribute>
     <!-- end <attributes>  here-->  
    </product>
</products>

是否可以在<attribute>内嵌套所有<attributes>个节点。

提前致谢!

1 个答案:

答案 0 :(得分:0)

我不知道SQL中的字符串连接(+)。我花了一个多星期的时间才想出一件小事。这就解决了我的问题。将来可能会帮助别人。

bcp "SELECT RTRIM(LTRIM(sku)) as sku, (SELECT 'AttributeName' AS [attribute/name],
'ProdName' AS [attribute/row/name], 
ProdName AS [attribute/row/value],
+'',  
'AttributeName' AS [attribute/name],
'color' AS [attribute/row/name], 
color AS [attribute/row/value]    
FROM Tbl_Product Where (SKU = TP.SKU) 
FOR XML PATH (''), ROOT('attributes'), Type)  

FROM Tbl_Product TP WHERE (SKU = 12345) 
FOR XML PATH ('product'), ROOT('products'),Type"   queryout "..\Desktop\sample.xml" -c -T