簡體   English   中英

如何刪除 SQL 中特定字符的部分字符串開頭和結尾

[英]How to remove part of string start and end with specific character in SQL

如何從該字符串中刪除以“ diffg ”開頭並以“ > ”結尾的部分字符串

DECLARE @XmlDocument nvarchar(max) =
'<NewDataSet>
    <Table diffgr:id="Table1" msdata:rowOrder="0">
       <ActionDate>2020/06/03</ActionDate>
       <ProductCode>4523</ProductCode>
       <ToDateOnTheWay>0</ToDateOnTheWay>
    </Table> 
    <Table diffgr:id="Table2" msdata:rowOrder="2">
       <ActionDate>2020/06/03</ActionDate>
       <ProductCode>0241445</ProductCode>
       <ToDateOnTheWay>0</ToDateOnTheWay>
       <InventoryFee>286295415</InventoryFee>
       <BuyFee>997545</BuyFee>
    </Table>                             
</NewDataSet>'

我不確定這正是你想要得到的,但你可以使用這樣的東西:

declare @newxml NVARCHAR(max) = '';
select @newxml += case when value like '%diffgr%' 
        then stuff(value,charindex('diffgr',value)-1,999,'') else value end + '>'
from string_split(@XmlDocument,'>')
select @newxml as newXMLDoc

在 XML 上使用CHARINDEX會導致災難。

真正做到這一點的方法是使用 XML 修改語句,並將您的 XML 存儲在實際的xml數據類型中。

我注意到您的 XML 缺少命名空間聲明,我已經添加了它們

DECLARE @XmlDocument xml =
'<NewDataSet xmlns:diffgr="someURI" xmlns:msdata="someURI">
    <Table diffgr:id="Table1" msdata:rowOrder="0">
       <ActionDate>2020/06/03</ActionDate>
       <ProductCode>4523</ProductCode>
       <ToDateOnTheWay>0</ToDateOnTheWay>
    </Table> 
    <Table diffgr:id="Table2" msdata:rowOrder="2">
       <ActionDate>2020/06/03</ActionDate>
       <ProductCode>0241445</ProductCode>
       <ToDateOnTheWay>0</ToDateOnTheWay>
       <InventoryFee>286295415</InventoryFee>
       <BuyFee>997545</BuyFee>
    </Table>                             
</NewDataSet>';

WHILE @XmlDocument.exist('NewDataSet/Table/@*') = 1
    SET @XmlDocument.modify('
        delete (NewDataSet/Table/@*)[1]
    ');

SELECT @XmlDocument;

db<>小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM