SQL替换空xml值

时间:2017-07-05 11:01:45

标签: sql-server tsql xpath xquery xml-dml

我是sql的初学者,我不知道如何找到问题的解决方案。

我有一个包含项目的表,一列包含xml值。我想检查一个字段是否存在并更新它。

我找到了修改现有xml值的方法,但是当它为NULL时它不起作用

有我的代码:

SELECT @xml=IDA_Xml,
   @isData = IDA_Xml.exist('(/Root/Data[1]/text())[1]')
FROM DATA
WHERE IDA_UId=@guid

If (@xml is NULL)
BEGIN
    -- Create a xml value with <Root></Root>
    -- It will be update later
    -- set isData to 0
END

IF (@isData = 0)
    UPDATE ItemData SET IDA_Xml.modify
    ('
        insert <Data Name = "Info">{sql:variable("@number")}</Data>
        into (/Root/*)[1]
    ')
    WHERE IDA_UId = @guid;
ELSE
    UPDATE ItemData SET IDA_Xml.modify
    ('
        replace value of (/Root/Data[1]/text())[1]
        with    sql:variable("@number")
    ')
    WHERE IDA_UId = @guid;

2 个答案:

答案 0 :(得分:1)

遵循您的代码结构

SELECT @xml=IDA_Xml,
   @isData = IDA_Xml.exist('(/Root/Data[1]/text())[1]')
FROM DATA
WHERE IDA_UId=@guid

If (@xml is NULL)
BEGIN
    UPDATE ItemData SET IDA_Xml =  CAST('<root/>' as XML)
    WHERE IDA_UId = @guid;
    SET @isData = 0;
END 

IF (@isData = 0)
    UPDATE ItemData SET IDA_Xml.modify
    ('
        insert <Data Name = "Info">{sql:variable("@number")}</Data>
        into (/Root/*)[1]
    ')
    WHERE IDA_UId = @guid;
ELSE
    UPDATE ItemData SET IDA_Xml.modify
    ('
        replace value of (/Root/Data[1]/text())[1]
        with    sql:variable("@number")
    ')
    WHERE IDA_UId = @guid;

但我最好使用单一更新重新构建它,而不是前两种更新

SET IDA_Xml =  CAST('construct your entire xml here' as XML)

答案 1 :(得分:1)

在这种情况下,大多数情况下最简单的方法是丢弃现有元素并将其作为新元素插入:

DECLARE @mockup TABLE(ID INT IDENTITY, Descr VARCHAR(100),YourXml XML);
INSERT INTO @mockup VALUES
 ('element exists','<root><element>test</element><SomeOther>blah</SomeOther></root>')
,('element doesn''t exist','<root><SomeOther>blah</SomeOther></root>')
,('element exists, but empty','<root><element/><SomeOther>blah</SomeOther></root>');

--At the end, all should be `<element>new</element>`

UPDATE @mockup SET YourXml.modify('delete (/root/element)[1]');
UPDATE @mockup SET YourXml.modify('insert <element>new</element> as first into (/root)[1]');

SELECT * FROM @mockup;