首页 > 解决方案 > PATINDEX 的意外结果

问题描述

我正在使用 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

标签: sqlsql-serverreplacepattern-matchingmatching

解决方案


据我所知,@IncorrectMatchIndex 字符串不包含匹配项%<EstmatedTime>%T%-%</EstmatedTime>%。T 和关闭之间没有破折号</EstmatedTime>

就在这里。因为字符串后面还有第二组标签,而且在第一个最后一个<EstimatedTime>之间肯定有一个“-”字符 T </EstimatedTime>


推荐阅读