2010-07-22 45 views
0

其他的方法,我有這樣的以下數據:處理這個TSQL文本操作

0297144600-4799    0297485500-5599 

的0297485500-5599根據觀察總是從左邊這這是一個簡單的方法31位字符。

但我想這樣做是預測以防萬一的數據是像下面這這意味着位置不再有效:

0297144600-4799  0297485500-5599  0297485600-5699 

正如你所看到的,我想第一個方法將在按空格分隔(「」),但由於空間數量未知(變化),我該如何採取這種方法呢?是否有任何方法可以找到它們之間的空間並縮小到1個空格(「」)。

BTW ...它需要在TSQL(MS SQL 2005)做的原因很不幸它是SSIS :(

我跟你的想法/建議公開。

感謝

+0

單行中會有多少個可能的數字分組?您是否感興趣僅檢索0297485500-5599,或者行中的任何給定值? – LittleBobbyTables 2010-07-22 23:59:22

+3

我能想到的最簡單的方法就是在進一步操作之前使用正則表達式替換函數將一個或多個空格轉換爲一個空格。可以,但需要CLR功能... – 2010-07-23 00:03:43

+0

不,我需要獲得0297144600-4799,0297485500-5599和0297485600-5699,具體取決於該線路。從數字組的可能性來看,它是未知的,但從觀察結果來看,總字符永遠不會得到100個字符 – dcpartners 2010-07-23 00:04:48

回答

1

假設您正在處理一條線的時間,你也可以試試這個:

DECLARE @InputString nvarchar(max) 
SET @InputString = '0297144600-4799  0297485500-5599  0297485600-5699' 
BEGIN 
WHILE CHARINDEX(' ',@InputString) > 0 -- Checking for double spaces 
    SET @InputString = 
    REPLACE(@InputString,' ',' ') -- Replace 2 spaces with 1 space 
END 
PRINT @InputString 

(直接從SQLUSA採取fnRemoveMultipleSpaces 1

2

我已經更新了我的答案了一下,現在我知道數字模式並不總是匹配。此代碼假定序列將以數字開頭和結尾,並由任意數量的空格分隔。

DECLARE @input nvarchar -- max in parens 
DECLARE @pattern nvarchar -- max in parens 
DECLARE @answer nvarchar -- max in parens 
DECLARE @pos int 
SET @input = '  0297144623423400-4799  5615618131201561561  0297485600-5699   ' 

-- Make sure our search string has whitespace at the end for our pattern to match 
SET @input = @input + ' ' 

-- Find anything that starts and ends with a number 
WHILE PATINDEX('%[0-9]%[0-9] %', @input) > 0 
BEGIN 
    -- Trim off the leading whitespace 
    SET @input = LTRIM(@input) 
    -- Find the end of the sequence by finding a space 
    SET @pos = PATINDEX('% %', @input) 
    -- Get the result out now that we know where it is 
    SET @answer = SUBSTRING(@input, 0, @pos) 
    SELECT [Result] = @answer 
    -- Remove the result off the front of the string so we can continue parsing 
    SET @input = SUBSTRING(@input, LEN(@answer) + 1, 8096) 
END 
+0

PATINDEX?我將探討此問題。 – dcpartners 2010-07-23 00:35:01

+0

該數字可以是任何內容,例如0297144600-4799,然後是0297144600-0297144699 。我該如何處理? – dcpartners 2010-07-23 00:50:07