更新SQL Server中的XML节点值

时间:2009-09-17 18:49:55

标签: sql-server xml tsql

我需要将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。哈哈,这总是让我们蠢蠢的小事。

2 个答案:

答案 0 :(得分:35)

您可以这样做:

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:为了获得价值,这样做会容易得多:

SELECT ProfileXML.value('(/ProblemProfile/GroupID)[1]', 'int') as ID
FROM dbo.profiles
WHERE id = 23

(除非您以后需要将XML作为SQL变量用于其他内容)

答案 1 :(得分:0)

更改元素内文本的最简单方法

UPDATE [TableName]
   SET  
      [fieldName].modify('replace value of (root/elementName/text())[1] with "wBob"')
GO