2014-06-12 3 views
1

일부 xml이 들어있는 nvarchar (max) 열이있는 테이블이 있습니다. 예를 들어SQL에서 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') 
나는 몇 가지 요소 이름을 변경하고 싶은

/다른 테이블에서 일부 XML을 생성하는 for xml path 선택 문 내에서 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> 

예를 들어

이 작업을 십자가에 조인하는 데 실패했습니다. 작동하지 못했고, 내가 접근하고 있는지도 모릅니다. 오른쪽 각도에서 t.

그것이 사람을 위해 더 쉽게 만들어 넣다, 나는 SQL 바이올린에 넣고했습니다 http://sqlfiddle.com/#!3/fd77c/3/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 
+0

그건 내가 원했던 것입니다. 고마워요! – stormCloud

관련 문제