Christian
Christian

Reputation: 1735

Use of logical and for an xquery delete in tsql

Is it possible to use a logical and operator with an xquery statement inside a stored procedure to delete an element only if its parent element has a specific value AND it has a specific value? Such as:

SET @profiles_xml = (SELECT profiles from tbl_applied_profiles WHERE profiles.value('(Profile/ID)[1]','int')= @profile_id)
    SET @profiles_xml.modify('
    delete
    if(/Profile/User/ID=sql:variable("@user_id")) and (/Profile/User/Activities/Activity/Name = sql:variable("@activity_name"))
    then (/Profile/User/Activities/Activity)
    else()
    ')

I would like to delete the Activity only if the User ID element and Activity Name element match the given parameters. The xml in profiles_xml looks like this:

<Profile>
  <ID>20</ID>
  <User>
    <ID>BC4A18CA-AFB5-4268-BDA9-C990DAFE7783</ID>
    <Name>somename</Name>
    <Activities>
      <Activity>
         <Name>activity1</Name>
      </Activity>
    </Activities>
  </User>
</Profile>

But in the future there will potentially be multiple elements in each and Multiple elements as children of the element.

Upvotes: 0

Views: 958

Answers (1)

Mikael Eriksson
Mikael Eriksson

Reputation: 139000

declare @XML xml = '
<Profile>
  <ID>20</ID>
  <User>
    <ID>BC4A18CA-AFB5-4268-BDA9-C990DAFE7783</ID>
    <Name>somename</Name>
    <Activities>
      <Activity>
         <Name>activity1</Name>
      </Activity>
    </Activities>
  </User>
</Profile>'

declare @user_id nvarchar(50) = '20'
declare @activity_name nvarchar(50) = 'activity1'

set @XML.modify('delete /Profile[ID = sql:variable("@user_id")]
                        /User/Activities/
                        Activity[Name = sql:variable("@activity_name")]') 

select @XML

Upvotes: 4

Related Questions