更新XML类型列的值

时间:2014-02-10 11:28:45

标签: sql sql-server xml

我有问题!我们有一个具有XML类型列的SQL Server表。此列有许多节点,其中一些节点有拼写错误的值 我想写一个脚本来更新所有错误拼写!问题是我不知道怎么做!
假设XML列中的一个节点名为TEST,其中一些节点的拼写错误值为MISSPELLED,我希望在更新后将其修改为CORRECT。 /> 这可能吗?如果可以的话怎么办?
提前谢谢。
/卡翁达

2 个答案:

答案 0 :(得分:0)

您可以通过以下方式修改XML列数据:

CREATE TABLE Test (C1 XML)
INSERT INTO Test 
VALUES ('<REF>
            <Person>
                <FirstName>John</FirstName>
                <LastName>Smith</LastName>
                <System>
                    <User><Systemid>System1</Systemid><Type>UserId</Type><Useridentity>Userid1</Useridentity></User>
                    <User><Systemid>System2</Systemid><Type>UserIdx</Type><Useridentity>Userid2</Useridentity></User>
                    <User><Systemid>System2</Systemid><Type>Department</Type><Useridentity>Finance</Useridentity></User>
                    <User><Systemid>System3</Systemid><Type>UserId</Type><Useridentity>Userid3</Useridentity></User>
                    <User><Systemid>System4</Systemid><Type>UserIdx</Type><Useridentity>Userid4</Useridentity></User>
                </System>
            </Person>
        </REF>
')


UPDATE [Test]
SET C1.modify('replace value of (/REF/Person/System/User/Type/text())[1] with "UserId"')
WHERE C1.value('(/REF/Person/System/User/Type/text())[1]', 'varchar(max)') LIKE '%UserIdx%'

更新:

对于列中的多个值更新,您需要编写如下脚本:

DECLARE @strSQL NVARCHAR(MAX)
DECLARE @Index INT
DECLARE @NodeCount INT

SET @Index = 1
SELECT @NodeCount = C1.value('count(/REF/Person/System/User/Type)', 'INT') from Test

WHILE @Index <= @NodeCount
BEGIN
    SET @strSQL = ' UPDATE [Test]
                    SET C1.modify(''replace value of (/REF/Person/System/User/Type/text())[' + CAST(@Index AS VARCHAR(10)) + '] with "UserId"'')
                    WHERE C1.value(''(/REF/Person/System/User/Type/text())[' + CAST(@Index AS VARCHAR(10)) + ']'', ''varchar(max)'') LIKE ''%UserIdx%'''

    EXEC(@strSQL)

    SET @Index = @Index + 1
END

答案 1 :(得分:0)

<REF><Person><FirstName>John</FirstName><LastName>Smith</LastName><System><User><Systemid>System1</Systemid><Type>UserId</Type><Useridentity>Userid1</Useridentity></User><User><Systemid>System2</Systemid><Type>UserIdx</Type><Useridentity>Userid2</Useridentity></User><User><Systemid>System2</Systemid><Type>Department</Type><Useridentity>Finance</Useridentity></User><User><Systemid>System3</Systemid><Type>UserId</Type><Useridentity>Userid3</Useridentity></User><User><Systemid>System4</Systemid><Type>UserIdx</Type><Useridentity>Userid4</Useridentity></User></System></Person></REF>