Sql Xquery如何替换更新查询中的文本

表被命名为MasterTable

ID 类型 BIGINT,

Name type VARCHAR(200)(出于某些原因存储xml类型数据)

Name type VARCHAR(200) (stores xml type data for some reasons)

Name 包含结构如下的数据

<en-US>SomeEnglishText</en-US><it-IT>SomeItalicText</it-IT>

当我需要 Update Master 表时,那时我需要将 Varchar 转换为 xml 然后有条件地更新/替换特定标签的value部分,即en-US/it-IT.

When I need to Update the Master Table then at that time I Need to cast the Varchar to xml then conditionally update / replace the value part of particular tag i.e either en-US / it-IT.

Name 列中也有 No data/tags 的可能性,所以我认为在插入数据时它会 Insert表中的空标记元素,如 <en-US></en-US><it-IT></it-IT>,所以 update 查询必须处理标签元素中的空值,即en-US/it-IT.

Also there are chances that No data/tags are there in Name column so I think at the time of Inserting data it would Insert empty tag elements in the table like <en-US></en-US><it-IT></it-IT>, so the update query must handle empty value in tag elements namely en-US/it-IT.

我正在尝试像以下更新查询一样进行操作.

I am trying to do it like following update query.

DECLARE @Str VARCHAR(200)

SET @Str = 'Test Text'

UPDATE [MasterTable]
SET [Name] = cast([MasterTable].[Name] as xml).modify('replace value of (en-US/text())[1] with sql:variable("@Str")')
WHERE [ID]=18

运行查询时出现以下错误

I getting following error when running the query

非法使用xml数据类型方法'modify'.在这种情况下需要一个非mutator方法.

Illegal use of xml data type method 'modify'. A non-mutator method is expected in this context.

推荐答案

您不能从 xml.modify 进行分配.修改直接作用于变量/列.您也不能在演员表上使用 modify.

You can not assign from a xml.modify. Modify works on the variable/column directly. You can also not use modify on a cast.

您可以将名称提取到xml变量中,修改xml然后将其放回表中.

You can extract the name to a xml variable, modify the xml and then put it back to the table.

declare @str varchar(200) = 'Test'
declare @xml xml

select @xml = cast(Name as xml)
from MasterTable
where ID = 18

set @xml.modify('replace value of (en-US/text())[1] with sql:variable("@Str")')

update MasterTable
set Name = cast(@xml as varchar(200))
where ID = 18

如果您需要一次处理多行,您可以使用包含 idname 列的表变量,其中 name 的数据类型是 xml 而不是 @xml 变量.

If you need this to work over more than one row at a time you can use a table variable with columns id and name where data type for name is xml instead of the @xml variable.

declare @str varchar(200) = 'Test Text'
declare @T table (ID int, Name xml)

insert into @T
select ID, cast(Name as xml)
from MasterTable
where Name is not null

update @T
set Name.modify('replace value of (en-US/text())[1] with sql:variable("@Str")')

update MasterTable
set Name = cast(T.Name as varchar(200))
from @T as T
where MasterTable.ID = T.ID

相关文章