2010-02-26 52 views
0

我有一個SQL Server表,其格式是這樣的一個字符串...如何從一個字符串在SQL Server中提取數值

nvarchar int nvarchar int nvarchar 

還有其他沒有明顯的分隔符,比一些字符是數字和其他人是阿爾法。

如何引用第二個int值?

+3

爲什麼你有多個值存儲在列中? – 2010-02-26 01:17:41

+1

爲什麼你有多個值存儲在列中*沒有分隔符*!?它不會比數據庫中的數據更糟...... – Aaronaught 2010-02-26 01:29:48

+0

想知道,是否有一種方法可以從最初的一個表列中創建多個列的表視圖? – Drejc 2010-02-26 08:07:07

回答

0

我會親自寫一個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 
+0

謝謝本 - 這完美的第一次 – cymorg 2010-02-28 12:43:33

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 
+0

謝謝DyingCactus,但這並不適用於所有可能的值 – cymorg 2010-02-28 12:44:58

+0

好吧,好奇,什麼是它沒有工作的字符串值之一? – DyingCactus 2010-03-01 03:10:04

相關問題