SQL 如何从字符串中提取数字?

SQL How to extract numbers from a string?

我正在 SQL 中进行查询,它应该能够从文本字符串的开头提取 different/random 长度的数字。

正文串:666鬼子号不是8888
文字串:12345 鬼子号码是我的密码,也就是6666.

我要上专栏

666
12345

使用 Substrinstr

的组合
SELECT Substr (textstring, 1,instr(textstring,' ') - 1) AS Output
FROM yourtable

结果:

OUTPUT
666
12345

如果开头有文字,请使用此选项,例如aa12345 devils number is my PIN, that is 6666. 因为它使用了 REGEXP_REPLACE 函数。

SELECT REGEXP_REPLACE(Substr (textstring, 1,instr(textstring,' ') - 1), '[[:alpha:]]','') AS Output
FROM yourtable

SQL Fiddle: http://sqlfiddle.com/#!4/8edc9/1/0

此版本使用正则表达式为您提供第一个数字,无论它前面是否有文本,并且不使用可怕的嵌套 instr/substr 调用:

SQL> with tbl(data) as (
     select '666 devils number is not 8888' from dual
     union
     select '12345 devils number is my PIN, that is 6666' from dual
     union
     select 'aa12345 devils number is my PIN, that is 6666' from dual
   )
   select regexp_substr(data, '^\D*(\d+) ', 1, 1, null, 1) first_nbr
   from tbl;

FIRST_NBR
---------------------------------------------
12345
666
12345

SQL>