简体   繁体   English

XQuery如果存在条件插入/替换

[英]XQuery if exists conditional insert / replace

What would the XQuery look like to check if a node exists, and if it does then run a replace statement, if not then an insert statement? XQuery会检查一个节点是否存在,然后运行一个替换语句,如果没有,那么插入语句是什么?

Here's what I have in mind. 这就是我的想法。 I want to store whether or not a user has read an important message in XML. 我想存储用户是否已阅读XML中的重要消息。 Here's what the data would look 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. 基本上这个XML告诉我用户已经读过一条消息,而另一条消息仍然需要被查看/读取。

I want to combine my insert / replace xquery into one statement. 我想将insert / replace xquery组合成一个语句。 Here's what I had in mind. 这就是我的想法。

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

I haven't found a really satisfactory way of doing this, but one of these might work for you. 我没有找到一个非常令人满意的方法,但其中一个可能对你有用。 I like the first technique better, but I'm annoyed that I haven't found a more elegant way of doing it. 我更喜欢第一种技术,但我很生气,我没有找到一种更优雅的方式。

Make sure the node always exists first 确保节点始终存在

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

Switching 交换

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM