我在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];
它不会替换日期时间值。据我所知,两个标签的命名空间是这个问题的原因。 如果我删除命名空间一切正常。
即使在XML中提到名称空间,是否可以替换标记文本?
答案 0 :(得分:2)
这应该有效:
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];
我们只需要声明命名空间,然后在需要的地方使用它。
在:
<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>
后:
<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>
此外,您可以查看此文档,了解有关处理命名空间的其他情况 - Handling Namespaces in XQuery