2014-01-02 2 views
1

테이블 열의 값이있는 노드를 추가하고 싶습니다. 내 최종 결과는 내가, 내가 그것을 XQuery를 수행 할 수 있습니다하지만 난 방법의 예를 찾을 수 있다고 생각 업데이트 할 DONT이선택 쿼리에서 xml 열에 노드를 추가하십시오.

<book title="you are not alone" author="Esther"> 
    <EDITIONS> 
    <edition year="2012"/> 
    <edition year="2013"/> 
    </EDITIONS> 
<seller> XYZ</seller> 
</book> 

같이 할

declare @table table (bookid int,xmlCol xml) 
insert into @table 
select 1, 
'<book title="you are not alone" author="Esther"> 
    <EDITIONS> 
    <edition year="2012"/> 
    <edition year="2013"/> 
    </EDITIONS> 
</book>' 

declare @table1 table(bookid int,seller varchar(5)) 
insert into @table1 
select 1,'xyz' 

select ??? 
from @table t 
inner join @table1 t1 
on t.bookid = t1.bookid 

이하 나의 예입니다 이것을하기 위해. 나는 전에 속성을 추가하는 것과 비슷한 질문을했고 Roman Pekar의 대답에 만족했습니다. add column value to an xml field as an attribute

+0

무엇을 시도 했습니까? 'FOR XML'을보십시오. http://technet.microsoft.com/en-us/library/ms178107.aspx – aaroncatlin

답변

3

없습니다. 그러나 XML 자체를 사용하고 필요한 새 요소 또는 속성을 추가하여 XML을 다시 만들 수 있습니다.

Roman Pekar 님이 다른 질문에 his answer을 사용 했으므로 사용법을 이해하면 그 답을 사용자가 여기에서 적용 할 수 있어야합니다.

새로운 루트 요소 book을 만들고 기존 요소 책의 특성을 추가하고 책에서 하위 요소를 추가 한 다음 sql:column을 사용하여 새 요소를 추가하여 값을 가져와야합니다.

select T.xmlCol.query('element book { 
            book/@*,     (:Add attributes from root node:) 
            book/*,      (:Add sub nodes from root node:) 
            element seller    (:Add the new element:) 
             {sql:column("T1.seller")} (:Get the value for the new node:) 
            }') 
from @table as T 
    inner join @table1 as T1 
    on T.bookid = T1.bookid 
2

하나의 솔루션 따라서 insert XML DML statement으로 modify method을 사용하는 것입니다

declare @TableWXmlCol table (bookid int,xmlCol xml) 
insert into @TableWXmlCol 
select 1, 
'<book title="you are not alone" author="Esther"> 
    <EDITIONS> 
    <edition year="2012"/> 
    <edition year="2013"/> 
    </EDITIONS> 
</book>' 

declare @TableWSeller table(bookid int,seller varchar(5)) 
insert into @TableWSeller 
select 1,'xyz' 

UPDATE a 
SET  xmlCol.modify('insert <seller>{sql:column("b.seller")}</seller> into (/book)[1]') 
FROM @TableWXmlCol a 
INNER JOIN @TableWSeller b ON a.bookid = b.bookid; 

SELECT * 
FROM @TableWXmlCol; 

출력 : 쿼리에서 기존의 XML에 요소를 추가 할 수있는 방법이

/* 
bookid xmlCol 
------ ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
1  <book title="you are not alone" author="Esther"><EDITIONS><edition year="2012" /><edition year="2013" /></EDITIONS><seller>xyz</seller></book> 
*/ 
관련 문제