【发布时间】:2019-05-14 22:12:57
【问题描述】:
我正在使用 PATINDEX 进行一些字符串操作,以修复 XML 中一些不正确的时间格式,例如(2018-12-20T17:00:00-05:00)。
我遇到的问题是 PATINDEX 在 @IncorrectMatchIndex 字符串中找到与 @Pattern 的匹配项。
您可以通过运行以下命令重新创建问题:
DECLARE @Pattern nvarchar(36) = '%<EstmatedTime>%T%-%</EstmatedTime>%',
@CorrectMatchIndex nvarchar(100) = '<DiscountedRate>263.34</DiscountedRate><EstmatedTime>2018-12-20T17:00:00-05:00</EstmatedTime></Rate>',
@CorrectMatchIndex2 nvarchar(94) = '<DiscountedRate>263.34</DiscountedRate><EstmatedTime>2018-12-20T17:00:00</EstmatedTime></Rate>',
@IncorrectMatchIndex nvarchar(296) = '<DiscountedRate>263.34</DiscountedRate><EstmatedTime>2018-12-20T17:00:00</EstmatedTime></Rate><Rate><Carrier>FedEx Freight</Carrier><Service>FEDEX_FREIGHT_PRIORITY</Service><PublishedRate>520.6</PublishedRate><DiscountedRate>272.04</DiscountedRate><EstmatedTime>2018-12-18T17:00:00</EstmatedTime>'
SELECT
PATINDEX(@Pattern, @CorrectMatchIndex) AS CorrectMatchIndex,
PATINDEX(@Pattern, @CorrectMatchIndex2) AS CorrectMatchIndex2,
PATINDEX(@Pattern, @IncorrectMatchIndex) AS IncorrectMatchIndex
【问题讨论】:
-
如果您长期需要此类工作,请考虑使用适当的 XML 解析器。我认为
PATINDEX很快就会失败。 -
所有这些结果对我来说都是正确的。为什么你认为他们错了?
-
我同意蒂姆的观点。 SQL Server 具有原生 XML 数据类型、XQuery 和 XPath 支持,不要为此使用 PATINDEX。
-
据我所知,@IncorrectMatchIndex 字符串不包含与 '%
%T%-% %' 的匹配项。 T 和结束 标记之间没有破折号。 -
@AlecThomas ,是的。
'<EstmatedTime>位于第 40 位。在接下来的时间里,您有一个'T'。然后你在字符串的末尾有一个连字符 (-) 和'</EstmatedTime>'('2018-12-18T17:00:00</EstmatedTime>') 返回的值 (40) 是正确的,因为那是匹配字符串的开始位置。
标签: sql sql-server replace pattern-matching matching