XQuery if conditional insert / replace exists

What would XQuery look like to check if a node exists, and if it does, run the replace statement, if not, then the insert statement?

Here is what I mean. I want to save if the user has read the important message in XML. Here's what the data looks like.

<usersettings>
    <message haveRead="0" messageId="23" ></message>
    <message haveRead="1" messageId="22" ></message>
</usersettings>

Basically this XML tells me that the user has read one message while the other message still needs to be viewed / read.

I want to combine my xquery insert / replace into a single statement. That's what I meant.

UPDATE WebUsers SET UserSettings.modify('

        declare default element namespace "http://www.test.com/test"; 

        IF a node exists with the messageId
            code to replace node with new update
        ELSE
            code to insert a new node with the provided variables
        ')

        WHERE Id = @WebUserId
+3
source share
1 answer

, . , , .

, node

DECLARE @messageID int;
SET @messageID=24;

DECLARE @myDoc xml;
SET @myDoc = 
'<usersettings>
    <message haveRead="0" messageId="23" >msg</message>
    <message haveRead="1" messageId="22" >msg</message>
</usersettings>';
SELECT @myDoc;


SET @myDoc.modify('
    insert
    if (count(//message[@messageId=sql:variable("@messageID")]) = 0)
    then <message haveRead="0">new msg</message>
    else()
         as last into (/usersettings)[1]
');

SELECT @myDoc;

--now do the rest, safe that the node exists

DECLARE @myDoc xml;
SET @myDoc = 
'<usersettings>
    <message haveRead="0" messageId="23" >msg</message>
    <message haveRead="1" messageId="22" >msg</message>
</usersettings>';
SELECT @myDoc;

DECLARE @messageID int;
SET @messageID=23;

IF @myDoc.exist('//message[@messageId=sql:variable("@messageID")]') = 1
BEGIN
    SET @myDoc.modify('replace value of (//message[@messageId=sql:variable("@messageID")]/text())[1]
                       with "test"')
END
ELSE
BEGIN
    SET @myDoc.modify('insert <message haveRead="0">new msg</message>
                       into (/usersettings)[1]')
END

SELECT @myDoc;
+5

Source: https://habr.com/ru/post/1755895/


All Articles