【问题标题】:SQL Query/function to remove alphabets only from endSQL查询/函数仅从末尾删除字母
【发布时间】:2015-08-06 12:26:20
【问题描述】:

在创建一个仅从末尾删除字符(字母)或直到数字出现在右侧的函数时需要帮助。

例如:

select fnStripRightAlpha('ABCD123F') --Should Return 'ABCD123'

select fnStripRightAlpha('PORT123G67KK') --Should Return 'PORT123G67'

select fnStripRightAlpha('123465') --Should Return '123465'

select fnStripRightAlpha('ABCDG') --Should Return ''

saw functions 删除了所有字母,但它们并没有解决我的目的,因为只删除最右边的字符。

有什么想法吗?

【问题讨论】:

    标签: sql sql-server sql-server-2008-r2


    【解决方案1】:

    假设您只有字母数字字符,您可以像这样使用PATINDEXSTUFFREVERSE

    查询

    SELECT
    ISNULL(REVERSE(STUFF(REVERSE(col),1,PATINDEX('%[0-9]%',REVERSE(col)) -1,'')),'') as col
    FROM
    (
        VALUES('ABCD123F'),('PORT123G67KK'),('123465'),('ABCDG')
    ) as tab(col)
    

    输出

    col
    ABCD123
    PORT123G67
    123465
    ''
    

    【讨论】:

      【解决方案2】:

      最简单的方法是

          declare @str varchar(100)
      set @str='ABCD123F'
      select substring(@str,1,len(@str)-patindex('%[0-9]%',reverse(@str))+1)
      

      【讨论】:

      • 简单但不适用于案例 2 和 4。返回 PORT123G67KABCD
      猜你喜欢
      • 1970-01-01
      • 2012-05-11
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      相关资源
      最近更新 更多