【问题标题】:SQL Server: Substring based on first two characters being a numberSQL Server:基于前两个字符的子字符串是数字
【发布时间】:2017-08-25 10:54:09
【问题描述】:

我有一个文本字段,想从该字段中提取一个 ID 号 - ID 始终以 8 开头,长度为 12 个字符(例如 899900014658),当前代码使用以下子字符串方法:

substring(textfield,charindex('8',textfield),12) as extractedID

这会提取以 8 开头的任何内容,因此我会在提取的 ID 字段中得到诸如“上午 8 点”、“二月 8 日”等结果。

有没有一种方法可以提取以 8 开头且第二个和第三个字符也是数字的任何内容?

编辑 - 使用 PATINDEX 解决

 SUBSTRING(SubmissionDiaryEntry,(PATINDEX('%8[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%',SubmissionDiaryEntry)),12)

【问题讨论】:

    标签: sql sql-server tsql substring


    【解决方案1】:

    如果我理解你的问题:

    Select *
     From  YourTable
     Where textfield like '8[0-9][0-9]%'
    

    【讨论】:

    • 对不起,我应该更清楚,它试图将 ID 提取为一个新字段,已使用 PATINDEX 和您上面建议的类似方法解决。谢谢
    • @GullitsMullet 不用担心。很高兴你得到正确的答案:)
    【解决方案2】:

    查看下方,可能会有所帮助:

    declare @textfield nvarchar(20) = '845456798234'
    
    select case when substring(@textfield, 2, 1) like '[0-9]' 
                    and substring(@textfield, 3, 1) like '[0-9]'  
                then substring(@textfield,charindex('8',@textfield),12) 
            else 'not valid'
            end 
            as extractedID
    
    -- test
    set @textfield = '8r5456798234'
    
    select case when substring(@textfield, 2, 1) like '[0-9]' 
                    and substring(@textfield, 3, 1) like '[0-9]'  
                then substring(@textfield,charindex('8',@textfield),12) 
            else 'not valid'
            end 
            as extractedID
    

    但是约翰的答案要简单得多,而且看起来正是您要找的。 下面只是为了澄清......,使用约翰的脚本,你的问题的答案是:

    select substring(textfield,charindex('8',textfield),12) as extractedID
    from yourTable
    where textfield like '8[0-9][0-9]%'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-15
      • 2014-03-21
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      • 2021-06-05
      • 2020-06-25
      相关资源
      最近更新 更多