2016-06-11 92 views
-1

我有這個xml,我想將它插入臨時表中,包括單個行中的<salesorpurchase>節點中的值。這可能嗎?在SQL Server 2008中刪除XML子節點元素

或者你能告訴我如何刪除<SalesOrPurchase>而不刪除它的內部文本?

<ItemServiceRet> 
    <ListID>80000012-1302270176</ListID> 
    <EditSequence>1302270195</EditSequence> 
    <Name>2nd Floor Shop</Name> 
    <FullName>2nd Floor Shop</FullName> 
    <IsActive>true</IsActive> 
    <SalesOrPurchase> 
     <Price>0.00</Price> 
     <AccountRef> 
      <ListID>800000B3-1302260225</ListID> 
      <FullName>Rent Income:Rent income 2ND FL:2nd Floor Shops</FullName> 
     </AccountRef> 
    </SalesOrPurchase> 
</ItemServiceRet> 
<ItemServiceRet> 
    <ListID>80000002-1277187768</ListID> 
    <EditSequence>1463398389</EditSequence> 
    <Name>VAT 16%</Name> 
    <FullName>VAT 16%</FullName> 
    <IsActive>true</IsActive> 
    <SalesOrPurchase> 
     <PricePercent>16.00</PricePercent> 
     <AccountRef> 
      <ListID>6B0000-1224749077</ListID> 
      <FullName>Vat account</FullName> 
     </AccountRef> 
    </SalesOrPurchase> 
</ItemServiceRet> 

回答

1

1)嘗試下面的查詢來從每一個ItemServiceRet元件數據插入到一個行(在此情況下,因爲有兩個ItemServiceRet元件兩行會被插入):

DECLARE @XmlData XML = N' 
<ItemServiceRet> 
    <ListID>80000012-1302270176</ListID> 
    <EditSequence>1302270195</EditSequence> 
    <Name>2nd Floor Shop</Name> 
    <FullName>2nd Floor Shop</FullName> 
    <IsActive>true</IsActive> 
    <SalesOrPurchase> 
     <Price>0.00</Price> 
... 
</ItemServiceRet>' 

SELECT ListID   = y.XmlCol.value('(ListID)[1]', 'VARCHAR(19)'), 
     EditSequence = y.XmlCol.value('(EditSequence)[1]', 'INT'), 
     -- ... 
     Price   = y.XmlCol.value('(SalesOrPurchase/Price)[1]', 'NUMERIC(9,2)'), 
     PricePercent = y.XmlCol.value('(SalesOrPurchase/PricePercent)[1]', 'NUMERIC(9,2)'), 
     ListID2   = y.XmlCol.value('(SalesOrPurchase/AccountRef/ListID)[1]', 'VARCHAR(19)') 
INTO #Items 
FROM (VALUES (@XmlData)) x(XmlCol)/*or @XmlData.nodes*/ 
CROSS APPLY x.XmlCol.nodes(N'ItemServiceRet') y(XmlCol) 

/* 
Results: 
(2 row(s) affected) 
*/ 

將該溶液使用兩種XML方法:nodes(將XML分解成許多行)和值(它從當前節點/元素中提取一個值)。

2)第二溶液是「刪除」SalesOrderHeader節點從而:

SELECT x.XmlCol.query(' 
    for $i in (ItemServiceRet) 
     return 
      <ItemServiceRet> 
       <ListID>{$i/ListID/text()}</ListID> 
       <IsActive>{$i/IsActive/text()}</IsActive> 
       <Price>{$i/SalesOrPurchase/Price/text()}</Price> 
       <PricePercent>{$i/SalesOrPurchase/PricePercent/text()}</PricePercent> 
       <AccountRef> 
        <ListID>{$i/SalesOrPurchase/AccountRef/ListID/text()}</ListID> 
        <FullName>{$i/SalesOrPurchase/AccountRef/FullName/text()}</FullName> 
       </AccountRef> 
      </ItemServiceRet> 
') AS NewXmlCol 
FROM (SELECT (@XmlData)) x(XmlCol) 
+0

不要忘記更換在我的例子使用具有適當的值的數據類型,最大lenght,精度和標度。 –