我有一列ntext数据类型而非XML。它存储所有xml数据。我需要更新记录中的xml节点。它抛出一个错误,说“错误使用xml数据类型方法'修改'。在此上下文中应该使用非mutator方法。”
begin transaction
declare @Cps_Id int;
set @Cps_Id = 236;
declare @Cps_Message nvarchar(1024);
set @Cps_Message = 'updating cpsia message with smoking';
update table_name
set column_name = CONVERT(xml,column_name).modify('replace value of (/root/ProductInformation/CPSIA/CpsiaDetails/Item[CpsiaId=sql:variable("@Cps_Id")]/CpsiaMessage/text())[1] with sql:variable("@Cps_Message")')
WHERE Convert(xml,column_name).exist('/root/ProductInformation/CPSIA/CpsiaDetails/Item[CpsiaId=sql:variable("@Cps_Id")]')=1
rollback
示例XML:
<root>
<ProductInformation>
<Name> Truck with Battery Charger</Name>
<Description>Fr.</Description>
<CPSIA>
<CpsiaDetails>
<Item>
<CpsiaId>456</CpsiaId>
<CpsiaMessage>waring</CpsiaMessage>
</Item>
<Item>
<CpsiaId>236</CpsiaId>
<CpsiaMessage>to health</CpsiaMessage>
</Item>
</CpsiaDetails>
</CPSIA>
</ProductInformation>
</root>
答案 0 :(得分:6)
您需要对XML数据类型使用modify方法。
begin transaction
declare @Cps_Id int;
set @Cps_Id = 236;
declare @Cps_Message nvarchar(1024);
set @Cps_Message = 'updating cpsia message with smoking';
select id, CONVERT(xml,[text]) txt into #tmp from SO5954359
select * from #tmp
update #tmp
set txt.modify('replace value of (/root/ProductInformation/CPSIA/CpsiaDetails/Item[CpsiaId=sql:variable("@Cps_Id")]/CpsiaMessage/text())[1] with sql:variable("@Cps_Message")')
select * from #tmp
drop table #tmp
rollback
然后,您可以通过将更新的临时表连接到密钥上的原始表来更新原始表。