【问题标题】:Unexpected results with PATINDEXPATINDEX 的意外结果
【发布时间】: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 ,是的。 '&lt;EstmatedTime&gt; 位于第 40 位。在接下来的时间里,您有一个 'T'。然后你在字符串的末尾有一个连字符 (-) 和 '&lt;/EstmatedTime&gt;' ('2018-12-18T17:00:00&lt;/EstmatedTime&gt;') 返回的值 (40) 是正确的,因为那是匹配字符串的开始位置。

标签: sql sql-server replace pattern-matching matching


【解决方案1】:

据我所知,@IncorrectMatchIndex 字符串不包含与 %&lt;EstmatedTime&gt;%T%-%&lt;/EstmatedTime&gt;% 的匹配项。 T 和结束 &lt;/EstmatedTime&gt; 之间没有破折号

是的,有。因为在字符串后面还有第二组&lt;EstimatedTime&gt; 标签,并且在first Tlast @ 之间肯定有一个'-' 字符987654325@

【讨论】:

    【解决方案2】:

    纯粹猜测,我怀疑你想要:

    DECLARE @Pattern nvarchar(300) = '%<EstmatedTime>[1-2][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]-[0-9][0-9]:[0-9][0-9]</EstmatedTime>%'
    

    然后返回0IncorrectMatchIndex

    当然,cmets 是对的,您确实应该为此使用 XQUERY。但是,我无法为此提供示例,因为您提供的 XML 数据都不是有效的 XML(例如,@CorrectMatchIndex'&lt;/Rate&gt;' 结尾,但该节点从未打开)。

    【讨论】:

    • 是的,为了简单起见,我没有在这个示例中复制整个 XML。感谢您的帮助,我会根据您的建议考虑 XQUERY。
    猜你喜欢
    • 1970-01-01
    • 2011-09-15
    • 2012-04-02
    • 2017-07-11
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多