Query to get only numbers from a string

2018-12-31 13:51发布

suppose I have data like this:

string 1: 003Preliminary Examination Plan   
string 2: Coordination005  
string 3: Balance1000sheet

The output I expect is

string 1: 003
string 2: 005
string 3: 1000

And I want to implement it in sql. Please help. Thanks in advance :)

8条回答
琉璃瓶的回忆
2楼-- · 2018-12-31 14:23

With the previous queries I get these results:

'AAAA1234BBBB3333' >>>> Output: 1234

'-çã+0!\aº1234' >>>> Output: 0

The code below returns All numeric chars:

1st output: 12343333

2nd output: 01234

declare @StringAlphaNum varchar(255)
declare @Character varchar
declare @SizeStringAlfaNumerica int
declare @CountCharacter int

set @StringAlphaNum = 'AAAA1234BBBB3333'
set @SizeStringAlfaNumerica = len(@StringAlphaNum)
set @CountCharacter = 1

while isnumeric(@StringAlphaNum) = 0
begin
    while @CountCharacter < @SizeStringAlfaNumerica
        begin
            if substring(@StringAlphaNum,@CountCharacter,1) not like '[0-9]%'
            begin
                set @Character = substring(@StringAlphaNum,@CountCharacter,1)
                set @StringAlphaNum = replace(@StringAlphaNum, @Character, '')
            end
    set @CountCharacter = @CountCharacter + 1
    end
    set @CountCharacter = 0
end
select @StringAlphaNum
查看更多
梦醉为红颜
3楼-- · 2018-12-31 14:30

Please try:

declare @var nvarchar(max)='Balance1000sheet'

SELECT LEFT(Val,PATINDEX('%[^0-9]%', Val+'a')-1) from(
    SELECT SUBSTRING(@var, PATINDEX('%[0-9]%', @var), LEN(@var)) Val
)x
查看更多
登录 后发表回答