SQL服务器xml修改插入方式条件插入

SQL Server xml modify insert method condtional insert

我有这个 xml,我想为变量中指定的 /COUNTRY/DisplayValue 插入一个 <TICKED> 节点和一个 <DISABLED> 节点,但前提是 <TICKED>节点不存在。

DECLARE @xml AS XML;

SET @xml = '
      <COUNTRY TICKOPTION="Y">
        <DisplayValue>IRELAND</DisplayValue>
        <ReportValue>[Hierarchy].[CIMSHierarchy].[Country Name].&amp;[IRELAND]</ReportValue>
        <TICKED>Y</TICKED>
      </COUNTRY>
      <COUNTRY TICKOPTION="Y">
        <DisplayValue>CANADA</DisplayValue>
        <ReportValue>[Hierarchy].[CIMSHierarchy].[Country Name].&amp;[CANADA]</ReportValue>
        <TICKED>Y</TICKED> 
      </COUNTRY>      
      <COUNTRY TICKOPTION="Y">
        <DisplayValue>INDIA</DisplayValue>
        <ReportValue>[Hierarchy].[CIMSHierarchy].[Country Name].&amp;[INDIA]</ReportValue>
        <TICKED>Y</TICKED> 
      </COUNTRY>'

DECLARE @HC_Country_DV AS VARCHAR(255);

SET @HC_Country_DV = 'CANADA'

SET @xml.modify('
insert (<TICKED>Y</TICKED>,<DISABLED>Y</DISABLED>) 
into (/COUNTRY[DisplayValue = sql:variable("@HC_Country_DV")])[1]')

SELECT @xml 

当我这样做时,我得到了 <TICKED>

的两个条目
<COUNTRY TICKOPTION="Y">
  <DisplayValue>IRELAND</DisplayValue>
  <ReportValue>[Hierarchy].[CIMSHierarchy].[Country Name].&amp;[IRELAND]</ReportValue>
  <TICKED>Y</TICKED>
</COUNTRY>
<COUNTRY TICKOPTION="Y">
  <DisplayValue>CANADA</DisplayValue>
  <ReportValue>[Hierarchy].[CIMSHierarchy].[Country Name].&amp;[CANADA]</ReportValue>
  <TICKED>Y</TICKED>
  <TICKED>Y</TICKED>
  <DISABLED>Y</DISABLED>
</COUNTRY>
<COUNTRY TICKOPTION="Y">
  <DisplayValue>INDIA</DisplayValue>
  <ReportValue>[Hierarchy].[CIMSHierarchy].[Country Name].&amp;[INDIA]</ReportValue>
  <TICKED>Y</TICKED>
</COUNTRY> 

我不太明白如何只插入一次 <TICKED> 节点,我在修改中使用了 "if" 条件但无法弄清楚。我考虑过 "delete" 修改方法来删除一个,但我想在这里问一下,看看你们是否可以再次帮助我...

but only if a <TICKED> node doesn't already exist.

添加对 TICKED 节点的检查。 and not(TICKED).

SET @xml.modify('
insert (<TICKED>Y</TICKED>,<DISABLED>Y</DISABLED>) 
into (/COUNTRY[DisplayValue = sql:variable("@HC_Country_DV") and not(TICKED)])[1]')