[英]Convert table to XML with attributes using T-SQL
我正在尝试转换表:
为了方便起见,我在此sqlfiddle中创建了表:
http://www.sqlfiddle.com/#!6/b2fde/1
我想按照以下示例将其转换为包含“ LabelID”(类型为INT-最初来自tblLabelAttributes)和“ XML_VALUE”(类型为XML
)的表。 因此,对于labelID = 688,应为:
<attributes>
<attribute attribute_id="1" value="2.00" />
<attribute attribute_id="2" value="3.00" />
<attribute attribute_id="3" value="60.00"/>
</attributes>
应该将"attribute_id"
设置为tblCustomAttributeSourceSchema
的AttributeID,将"value"
设置为tblLabelAttributes
的值。
如果“ tblLabelAttributes”中的属性值为null,则该LabelID的XML中应缺少“属性”记录。
我对SQL Server中的XML功能不是很熟悉。 我正在寻找如何将数据转换为这样的XML。 任何帮助将不胜感激。
在查询中使用FOR XML:
SELECT *
FROM tblCustomAttributeSourceSchema FOR XML AUTO
SELECT *
FROM tblLabelAttributes FOR XML AUTO
另外,您可以在t-sql代码中创建自己的XML:
SELECT LabelID AS "@LabelID",
col1 AS "Attributes/col1",
col2 AS "Attributes/col2"
FROM tblLabelAttributes
FOR XML PATH('LabelID')
给出这样的输出:
<LabelID LabelID="688">
<Attributes>
<col1>2.00</col1>
<col2>3.00</col2>
</Attributes>
</LabelID>
好吧,如果代码完全像您的小提琴一样,您似乎会遇到一些问题:
我为自己的工作做了很多xml解析和创建工作,因此这里有一个示例:
; WITH d AS
(
SELECT
*
, ROW_NUMBER() OVER(PARTITION BY LabelId ORDER BY val) AS rwn
FROM tblLabelAttributes
UNPIVOT (val FOR col IN (col1, col2, col3)) AS upvt
)
, distincts AS
(
SELECT DISTINCT LabelId
FROM d
)
Select
LabelId AS "@LabelId"
, (
SELECT
val AS "@value"
, rwn AS "@attribute_id"
FROM d y
WHERE y.LabelId = x.LabelId
FOR XML PATH('attribute'), TYPE
)
From distincts x
FOR XML PATH('attributes'), ROOT('ROOT')
一般而言,嵌套选择与xml创建非常有效,因为您有时需要显示子节点关系和恕我直言,它们通过在where子句中将内部对象与外部对象进行连接来很好地实现此目的。 您还可以通过有时将某些部分注释为“ for xml ...”来告诉您正在执行的级别。 我通常从最低的节点构建一个好的xml结构,然后往树上爬。 这样,如果我需要调试某些内容,则可以注释掉最后一段,并看到多行中存在xml的一部分。 在此示例中,如果我在最后一行注释掉,则分组将为“ LabelId”。
略微调整版本以适合问题中的规范:
; WITH d AS
(
SELECT
*
, ROW_NUMBER() OVER(PARTITION BY LabelId ORDER BY val) AS rwn
FROM tblLabelAttributes
UNPIVOT (val FOR col IN (col1, col2, col3)) AS upvt
)
, distincts AS
(
SELECT DISTINCT LabelId
FROM d
)
Select
LabelId AS "@LabelId"
, (
SELECT
val AS "@value"
, rwn AS "@attribute_id"
FROM d y
WHERE y.LabelId = x.LabelId
FOR XML PATH('attribute'), TYPE, ROOT('attributes')
)
From distincts x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.