我需要将 GroupID 字段更新为 0。我已经弄清楚如何检索该值,但现在更新它时遇到问题。
任何帮助都会很棒!
<ProblemProfile>
<GroupID>-1</GroupID>
<LayoutID>1</LayoutID>
<MyQueries>false</MyQueries>
</ProblemProfile>
Declare @Result xml
set @Result = convert(xml,(select ProfileXML from profiles where id = 23))
SELECT x.value('.', 'int') ID
FROM @Result.nodes('/ProblemProfile/GroupID') as R(x)
更新
我现在需要做的是更新每一行的值为 'foo' 的 GroupID
declare @foo int
set @foo = -1
UPDATE profiles
SET ProfileXML.modify('replace value of (/ProblemProfile/GroupID/text())[1] with "0"')
WHERE ProfileXML.value('(/ProblemProfile/GroupID)[1]', 'int') = @foo
这只会更新满足此条件的第一行。我将如何更新每一行?
更新 2 该声明有效。事实证明,第一个节点的数据库结构可能不同。一个简单的//GroupID...etc 更新每一行。总是被愚蠢的小事绊倒哈哈。
最佳答案
你可以这样做:
UPDATE
dbo.profiles
SET
ProfileXML.modify('replace value of (/ProblemProfile/GroupID/text())[1] with "0"')
WHERE
id = 23
在 SQL Server 2005 XQuery and XML-DML 上查看这篇文章有关您可以使用 .modify
关键字执行的操作(插入、删除、替换等)的更多详细信息。
马克
PS:为了获得值(value),这样做会容易得多:
SELECT ProfileXML.value('(/ProblemProfile/GroupID)[1]', 'int') as ID
FROM dbo.profiles
WHERE id = 23
(当然,除非您以后需要将 XML 作为 SQL 变量用于其他用途)
关于sql-server - 更新 SQL Server 中的 XML 节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1440666/