SQL query/function 从字符串中提取第一个数字?不仅仅是第一个数字,而是整个数字,直到我们找到一个非数字值

SQL query/function to extract the first number from a string? not just the 1st numerical digit but the entire number until we hit a non-numeric value

我有两个输入字符串,看起来像 'London 350 Paris 456 eu iu' 和 'New York 154 Seattle 890 pc appl iu'。

现在,我需要字符串中的第一个数字。所以 query/function 需要遍历整个字符串,并从第一次看到数字和第一次遇到非数字开始获取所有数字。

因此在这种情况下,输出应分别为“350”和“154”。

使用Patindexsubstring

declare @str varchar(100) = 'London 350 Paris 456 eu iu'

select left(partialString,patindex('%[a-z]%',partialString)-1) 
    from (select partialString = substring(@str, patindex('%[0-9]%',@str), len(@str)))a

这样就可以得到第一个号码了

DECLARE @VAR VARCHAR(MAX) = 'London 350 Paris 456 eu iu'

SELECT SUBSTRING(@VAR, PATINDEX('%[0-9]%', @VAR), PATINDEX('%[^0-9]%', SUBSTRING(@VAR, PATINDEX('%[0-9]%', @VAR), 100)))

SQL 服务器中的字符串操作很棘手。这是一种方法:

select t.str, left(v.str, patindex('%[^0-9]%', v.str + ' '))
from (values ('London 350 Paris 456 eu iu')) t(str) cross apply
     (values(stuff(t.str, 1, patindex('%[0-9]%', t.str + '0') - 1, ''))) v(str);

Here 是一个 db<>fiddle.