【问题标题】:tsql - extract only a portion of a dynamic stringtsql - 仅提取动态字符串的一部分
【发布时间】:2016-04-20 22:31:15
【问题描述】:

我有一个表格,其中有一列包含一个字符串,例如:

xx-xx-xxx-84
xx-25-xxx-xx
xx-xx-123-xx

我想继续只查询数字,但正如您所见,数字每次都放在字符串中的不同位置。是否可以只查询字符串中的数字?

谢谢你, 感谢您的宝贵时间!

【问题讨论】:

标签: sql tsql


【解决方案1】:

这需要重复应用字符串函数。一种有助于所有嵌套的方法是使用OUTER APPLY。像这样的:

select t3.col
from t outer apply
     (select t.*, patindex(t.col, '[0-9]') - 1 as numpos) t1 outer apply
     (select t1.*, substring(t1.col, t1.numpos, len(t1.col)) as col2) t2 outer apply
     (select t2.*,
             (case when col2 like '%-%'
                   then substring(t2.col, charindex('-', t2.col))
                   else t2.col
              end) as col3
    ) t3

【讨论】:

    【解决方案2】:

    简单的方法(确定是否只有 'x' 和 '-' 在字符串中):

    SELECT REPLACE(REPLACE(s,'x',''),'-','') FROM T
    

    或者如果X 可以是任何非数字字符,那么使用PATINDEX() function

    SELECT S, SUBSTRING(S,
                        PATINDEX('%[0-9]%',s),
                        PATINDEX('%[0-9][^0-9]%',s)
                        +PATINDEX('%[0-9]',s)
                        +1
                        -PATINDEX('%[0-9]%',s)) as digit
    FROM T
    

    【讨论】:

      猜你喜欢
      • 2023-02-20
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      相关资源
      最近更新 更多