【问题标题】:getting the second occurrence of a substring with PatIndex使用 PatIndex 获取第二次出现的子字符串
【发布时间】:2020-10-30 22:59:09
【问题描述】:

通过此查询,我从地址获取邮政编码并且它可以工作,但在某些情况下地址编号的长度为 5,所以我得到这个而不是邮政编码,有没有机会得到最后一次出现有 PatIndex 吗?

SELECT address,IIF((PatIndex('%[0-9][0-9][0-9][0-9][0-9]%', address)>0), substring(address, PatIndex('%[0-9][0-9][0-9][0-9][0-9]%', address), 5) , NULL) AS postalCode
from table 

【问题讨论】:

    标签: sql substring patindex


    【解决方案1】:

    如果你想得到最后一次出现

    1. 反向地址
    2. 在反向地址中找到第一个匹配 PatIndex
    3. 反转第一个匹配的子字符串

    这样

    SELECT address,IIF((PatIndex('%[0-9][0-9][0-9][0-9][0-9]%', address)>0), reverse(substring(reverse(address), PatIndex('%[0-9][0-9][0-9][0-9][0-9]%', reverse(address)), 5)) , NULL) AS postalCode
    from tbl
    

    Run with db<>fiddle

    【讨论】:

      猜你喜欢
      • 2020-02-26
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      • 2019-07-02
      • 2014-08-08
      • 1970-01-01
      相关资源
      最近更新 更多