代码之家  ›  专栏  ›  技术社区  ›  cymorg

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

  •  0
  • cymorg  · 技术社区  · 16 年前

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

    nvarchar int nvarchar int nvarchar
    

    除了一些字符是数字,其他字符是字母之外,没有明显的分隔符。

    如何引用第二个int值?

    3 回复  |  直到 16 年前
        1
  •  0
  •   Ben Dempsey    16 年前

    我将亲自编写一个clr函数并使用字符串拆分函数。 以下是一些我认为有效的代码:

    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
    
        2
  •  2
  •   user121301    16 年前

    一种方法是使用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
    
        3
  •  0
  •   bendewey    16 年前

    本文关于在SQL Server中使用正则表达式可能会有所帮助。

    Regular Expressions Make Pattern Matching And Data Extraction Easier

    推荐文章