如何在考虑XML名称空间的情况下替换T-SQL中的XML标记文本

如何在考虑XML名称空间的情况下替换T-SQL中的XML标记文本,xml,tsql,replace,namespaces,Xml,Tsql,Replace,Namespaces,我在T-SQL中有以下代码: declare @x1 xml = '<ScheduleDefinition xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><StartDateTime xmlns="http://schemas.microsoft.com/sqlserver/reporting/2010/03/01/Report

我在T-SQL中有以下代码:

declare @x1 xml = '<ScheduleDefinition xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><StartDateTime xmlns="http://schemas.microsoft.com/sqlserver/reporting/2010/03/01/ReportServer">2018-02-06T00:00:00.000+10:00</StartDateTime></ScheduleDefinition>'; 
select @x1 as [@x1]; 

declare @now datetime = {d'2018-02-07'}; 
set @x1.modify('replace value of (/ScheduleDefinition/StartDateTime/text())[1] with sql:variable("@now")'); 
select @x1 as [@x1]; 
declare@x1xml='2018-02-06T00:00:00.000+10:00';
选择@x1作为[@x1];
声明@now datetime={d'2018-02-07'};
set@x1.modify('ScheduleDefinition/StartDateTime/text())[1]的值替换为sql:variable(@now”);
选择@x1作为[@x1];
它不替换日期时间值。据我所知,这两个标记的名称空间都是导致此问题的原因。 如果我删除名称空间,一切正常

即使在XML中提到名称空间,也可以替换标记文本吗?

这应该可以:

declare @x1 xml = '<ScheduleDefinition xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><StartDateTime xmlns="http://schemas.microsoft.com/sqlserver/reporting/2010/03/01/ReportServer">2018-02-06T00:00:00.000+10:00</StartDateTime></ScheduleDefinition>'; 
select @x1 as [@x1]; 

declare @now datetime = {d'2018-02-07'}; 
set @x1.modify('declare namespace NS = "http://schemas.microsoft.com/sqlserver/reporting/2010/03/01/ReportServer";  replace value of (/ScheduleDefinition/NS:StartDateTime/text())[1] with sql:variable("@now")'); 
select @x1 as [@x1]; 
declare@x1xml='2018-02-06T00:00:00.000+10:00';
选择@x1作为[@x1];
声明@now datetime={d'2018-02-07'};
set@x1.modify('declare namespace NS='http://schemas.microsoft.com/sqlserver/reporting/2010/03/01/ReportServer“将(/ScheduleDefinition/NS:StartDateTime/text())[1]的值替换为sql:variable(“@now”);
选择@x1作为[@x1];
我们只需要声明名称空间,然后在需要的地方使用它

之前:

<ScheduleDefinition xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <StartDateTime xmlns="http://schemas.microsoft.com/sqlserver/reporting/2010/03/01/ReportServer">2018-02-06T00:00:00.000+10:00</StartDateTime>
</ScheduleDefinition>

2018-02-06T00:00:00.000+10:00
之后:

<ScheduleDefinition xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <StartDateTime xmlns="http://schemas.microsoft.com/sqlserver/reporting/2010/03/01/ReportServer">2018-02-07T00:00:00.000</StartDateTime>
</ScheduleDefinition>

2018-02-07T00:00:00.000

此外,您还可以查看此文档,了解处理名称空间的其他情况-

非常感谢您提供的解决方案和链接!我还有一个问题:为什么不需要声明xmlns:xsd和xmlns:xsi?