如何检查值中的前一个或前两个或前三个字符是字母

时间:2019-04-17 11:04:21

标签: sql sql-server tsql sql-server-2000

我有一个IDNumber列的表,其中包含所有数字或字母数字,其中前两个或前三个或前三个字符是字母。我要做的就是从该值中删除那些字母。

请注意,数据库位于SQL Server 2000中。

例如:

1430112345679 (This is OK)
PO02456977785 (Remove first two letters)
C035343542654 (Remove first letter)
QPD1236548    (Remove first three letters)

2 个答案:

答案 0 :(得分:6)

这应该在SQL Server的任何受支持版本中执行所需的操作:

select idNumber, stuff(idNumber, 1, patindex('%[0-9]%', idNumber) - 1, '')

Here是db <>小提琴。

在很长一段时间以来一直不受支持的SQL Server 2000中,您可以做一些更暴力的事情:

select (case when idNumber like '[0-9]%' then idNumber
             when idNumber like '_[0-9]%' then substring(idNumber, 2, len(idNumber))
             when idNumber like '__[0-9]%' then substring(idNumber, 3, len(idNumber))
             when idNumber like '___[0-9]%' then substring(idNumber, 4, len(idNumber))
             . . . -- however many clauses you need
        end)

或使用LIKE

select (case when left(idNumber, 1) between '0' and '9' then idNumber
             when substring(idNumber, 2, 1) between '0' and '9'
             then substring(idNumber, 2, len(idNumber))
             when substring(idNumber, 3, 1) between '0' and '9'
             then substring(idNumber, 3, len(idNumber))
             when substring(idNumber, 4, 1) between '0' and '9'
             then substring(idNumber, 4, len(idNumber))
             . . . -- however many clauses you need
        end)

答案 1 :(得分:4)

PATINDEX在SQL Server 2000中可用。使用它:

SELECT val, SUBSTRING(val, PATINDEX('%[0-9]%', val), LEN(val)) AS newval
FROM (
    SELECT '1430112345679' AS val UNION ALL
    SELECT 'PO02456977785' UNION ALL
    SELECT 'C035343542654' UNION ALL
    SELECT 'QPD1236548'
) AS x

Result