如何从SQL Server中的字符串中提取数值

时间:2010-02-26 00:54:00

标签: sql-server string function

我在SQL Server表中有一个字符串,其格式如下...

nvarchar int nvarchar int nvarchar

除了一些字符是数字而其他字符是alpha时,没有明显的分隔符。

如何引用第二个int值?

3 个答案:

答案 0 :(得分:2)

一种方法是使用patindex功能:

declare @s varchar(100)
declare @i1 int
declare @s2 varchar(100)
declare @i2 int
declare @s3 varchar(100)
declare @i3 int
declare @s4 varchar(100)
declare @i4 int
declare @secondInt int

set @s = 'alpha123beta3140gamma789'

set @i1 = PATINDEX('%[0-9]%', @s)
set @s2 = SUBSTRING(@s, @i1, 100)
set @i2 = PATINDEX('%[^0-9]%', @s2)
set @s3 = SUBSTRING(@s2, @i2, 100)
set @i3 = PATINDEX('%[0-9]%', @s3)
set @s4 = SUBSTRING(@s3, @i3, 100)
set @i4 = PATINDEX('%[^0-9]%', @s4)

set @secondInt = CAST(SUBSTRING(@s4, 1, @i4-1) as int)

select @s, @secondInt

答案 1 :(得分:0)

有关在SQL Server中使用正则表达式的这篇文章可能会有所帮助。

Regular Expressions Make Pattern Matching And Data Extraction Easier

答案 2 :(得分:0)

我个人会写一个CLR函数并使用字符串SPLIT函数。 以下是我认为有用的代码:

Declare @Result Table
(
    stringval varchar(100),
    numvalue decimal(18,4)
)

Declare @Test  varchar(100)
Declare @index int
Declare @char char(1)
Declare @currentVal varchar(100)
Declare @prevVal varchar(100)
Declare @currentType char(1)
Declare @nextType char(1)

Set @index = 0
Set @Test = 'a100.4bb110ccc2000'

Set @currentVal = ''
Set @currentType = 's'

While @index <= LEN(@Test)
Begin
    Set @index = @index + 1
    Set @char = SUBSTRING(@Test,@index,1)       

    Set @nextType = CASE WHEN PATINDEX('[^0-9.]', @char) > 0 then 's' else 'n' end

    If @currentType <> @nextType 
    begin
        if @currentType = 'n'
            insert into @Result(stringval,numvalue) values(@prevVal,@currentVal)
        Set @prevVal = @currentVal
        set @currentVal = ''
        set @currentType = @nextType
    end

    SEt @currentVal = @currentVal + @char


ENd

Select * FROM @Result