我有一个表,nvarchar(max)列中包含一些xml。
例如:
Create table ta_test (xmlstring varchar(max), otherData varchar(10))
insert into ta_test values
('<items><item attr1="1" attr2="2"/><item attr1="1" attr2="2"><subitem attr1="1"/></item></items>','test1'),
('<items><item attr1="1" attr2="2"/><item attr1="1" attr2="2"><subitem attr1="1"/></item></items>','test2'),
('<items><item attr1="1" attr2="2"/><item attr1="1" attr2="2"><subitem attr1="1"/><subitem attr1="1"/></item></items>','test3')
我想从for xml path
select语句中重命名xml数据中的一些元素/属性,该语句从其他一些表生成一些xml。
例如:
select
otherdata as '@OtherData',
cast(xmlstring as xml)
from ta_test
for xml path ('test'), type
将以格式:
返回xml<test OtherData="test1">
<items>
<item attr1="1" attr2="2"/>
<item attr1="1" attr2="2">
<subitem attr1="1"/>
</item>
</items>
</test>
但我希望xml类似于:
<test OtherData="test2">
<NewItemsNodeName>
<NewItemNodeName NewAttr1Name="1" NewAttr2Name="2"/>
<NewItemNodeName NewAttr1Name="1" NewAttr2Name="2">
<subitem NewAttr1Name="1"/>
</NewItemNodeName>
</NewItemsNodeName>
</test>
我一直试图通过交叉加入尝试不成功,但我无法让它工作,我也不知道我是否接近它正确的角度。
Encase it让任何人都更容易,我把它放在一个sql小提琴中:http://sqlfiddle.com/#!3/fd77c/3/0
有人可以帮忙吗?
答案 0 :(得分:1)
select T1.otherData as '@OtherData',
(
select I.X.value('@attr1', 'int') as '@NewAttr1Name',
I.X.value('@attr2', 'int') as '@NewAttr2Name',
(
select S.X.value('@attr1', 'int') as '@NewAttrName1'
from I.X.nodes('subitem') as S(X)
for xml path('subitem'), type
)
from T2.X.nodes('/items/item') as I(X)
for xml path('NewItemNodeName'), root('NewItemsNodeName'), type
)
from ta_test as T1
cross apply (select cast(T1.xmlstring as xml).query('.')) as T2(X)
for xml path('test'), type