Delete xml node from SQL Server 2008 r2 table column based on attribute value

自作多情 提交于 2020-01-06 04:00:26

问题


I have an xml structure as follows

<DifficultyRule xmlns="urn:gjensidige:processguide:201201">
 <Id>fc39f423-05c0-4de9-ae46-12fe3c0c279b</Id>
 <Code>5595e558-7d10-4767-86dc-5d16f24b8151_Code</Code>
 <Author />
 <Updated>9/5/2012</Updated>
 <Sequence>0</Sequence>
 <FromControls>
 <Control>
  <Code>oiuyui</Code>
  <Id>70579cbe-c0b5-4b49-a7b8-6201af388f59</Id>
  <FilterValues>
     <FilterValue xmlns:p5="urn:gjensidige:processguide:201201" p5:Id="b897f3ac-b40f-4b96-b438-eb156a26457e" p5:Code="e" p5:LookupId="3fa26ce7-4031-4e41-92cb-50d8ce56d262" />
   </FilterValues>
 </Control>
</FromControls>
<DifficultyCode>Red</DifficultyCode>
</DifficultyRule>

I am trying to delete the FilterValue node in the xpath

/qn:DifficultyRule/qn:FromControls/qn:Control/qn:FilterValues/qn:FilterValue 

based on the value of the p5:Id attribute but I am confused as to why nodes are not getting deleted.

Below is the script I'm using:

declare @lookupvalueId varchar(50)
declare @ruleId varchar(50)

set @lookupvalueId = 'b897f3ac-b40f-4b96-b438-eb156a26457e'
set @ruleId = 'fc39f423-05c0-4de9-ae46-12fe3c0c279b'

;WITH XMLNAMESPACES ('urn:gjensidige:processguide:201201' as qn)
update pdr_processdefinitionrule
set PDR_RuleXml.modify('delete (/qn:DifficultyRule/qn:FromControls/qn:Control/qn:FilterValues/qn:FilterValue[@Id=sql:variable("@lookupvalueId")])')
where pdr_guid = @ruleId

What am I missing? Any guidance will be appreciated


回答1:


Well, since your XML attribute id is the XML namespace with the prefix p5, you must also declare and use that second XML namespace in your code:

declare @lookupvalueId varchar(50)
declare @ruleId varchar(50)

set @lookupvalueId = 'b897f3ac-b40f-4b96-b438-eb156a26457e'
set @ruleId = 'fc39f423-05c0-4de9-ae46-12fe3c0c279b'

;WITH XMLNAMESPACES ('urn:gjensidige:processguide:201201' as qn,
                     'urn:gjensidige:processguide:201201' as p5)
update 
    pdr_processdefinitionrule
set 
    PDR_RuleXml.modify('delete (/qn:DifficultyRule/qn:FromControls/qn:Control/qn:FilterValues/qn:FilterValue[@p5:Id=sql:variable("@lookupvalueId")])')
where 
    pdr_guid = @ruleId

See that second XML namespace definition for p5? See the use of that XML namespace in the qn:FilterValue[@p5:Id=sql:variable("@lookupvalueId")] expression?



来源:https://stackoverflow.com/questions/12296091/delete-xml-node-from-sql-server-2008-r2-table-column-based-on-attribute-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!