SQL to find first non-numeric character in a strin

2019-01-15 19:44发布

I inherited a table with identifiers in a format [nonnumericprefix][number]. For example (ABC123; R2D2456778; etc). I was wondering if there was a good way to split this in SQL into two fields, the largest integer formed from the right side, and the prefix, for example (ABC, 123; R2D, 2456778; etc). I know I can do this with a cursor, C# code, etc - and I will if I have to - but I don't run into things I cannot do fast and easily in SQL very often, so I thought I'd post it here.

3条回答
霸刀☆藐视天下
2楼-- · 2019-01-15 20:02

You could try something like

DECLARE @Table TABLE(
        Val VARCHAR(50)
)

INSERT INTO @Table SELECT 'ABC123'
INSERT INTO @Table SELECT 'R2D2456778'

SELECT  *,
        LEFT(Val,LEN(Val) - (PATINDEX('%[^0-9]%',REVERSE(Val)) - 1)),
        RIGHT(Val,(PATINDEX('%[^0-9]%',REVERSE(Val)) - 1))      
FROM    @Table
查看更多
Rolldiameter
3楼-- · 2019-01-15 20:07
  1. Reverse the string
  2. Use PATINDEX to find the first occurrence of a non numeric field
  3. Use the LEFT function to return the numeric portion of the string

Code sample

DECLARE @myString varchar(100);
DECLARE @largestInt int;

SET @myString = 'R2D2456778'

SET @mystring = REVERSE(@myString);
SET @largestInt = LEFT(@myString, PATINDEX('%[a-z]%', @myString) - 1)

PRINT ( CONVERT(varchar(100), @largestInt) )
查看更多
冷血范
4楼-- · 2019-01-15 20:12

You can use PATINDEX with a pattern like '%[^0123456789]%' or '%[^0-9]%' to find the position of the first non-numeric character

查看更多
登录 后发表回答