2011-11-16 101 views
1

我有字母數字字符A-Z和0-9T-SQL字符串處理,替換,比較,模式匹配,正則表達式

字符和數字被包含在字符串中的短字符串。

我想剝離空格,並將每個字符串與僅匹配其中一個的「模式」進行比較。模式使用A表示任何字符A-Z和9表示任何0-9。

的6種模式是:

A99AA 
A999AA 
A9A9AA 
AA99AA 
AA999AA 
AA9A9AA 

我有這些與另一列的表,用正確地定義空間: -

pattern PatternTrimmed 
A9 9AA A99AA 
A99 9AA A999AA 
A9A 9AA A9A9AA 
AA9 9AA AA99AA 
AA99 9AA AA999AA 
AA9A 9AA AA9A9AA 

我使用SQL Server 2005中,和我不想讓34個替換語句將每個字符和數字改爲A和9。

有關如何以簡潔的方式實現此目的的建議,請。

這是我想避免什麼: -

update postcodes set Pattern = replace (Pattern, 'B', 'A') 
update postcodes set Pattern = replace (Pattern, 'C', 'A') 
update postcodes set Pattern = replace (Pattern, 'D', 'A') 
update postcodes set Pattern = replace (Pattern, 'E', 'A') 

update postcodes set Pattern = replace (Pattern, '0', '9') 
update postcodes set Pattern = replace (Pattern, '1', '9') 
update postcodes set Pattern = replace (Pattern, '2', '9') 

基本上,我試圖把英國郵政編碼的類型在一個電話中心,由一個imbecile,模式匹配輸入的郵編對上述6種模式之一,並找出插入空間的位置。

+0

更新郵政編碼設定模式=取代(圖案, 'B', 'A') 更新郵政編碼設定模式=取代(圖案, 'C', 'A') 更新郵政編碼設定模式=取代(圖案,「d ','A') update postcodes set Pattern = replace(Pattern,'E','A') 等 – cometbill

回答

1

什麼是這樣的:

Declare @table table 
(
ColumnToCompare varchar(20), 
AmendedValue varchar(20) 
) 

Declare @patterns table 
(
Pattern varchar(20), 
TrimmedPattern varchar(20) 
) 

Insert Into @table (ColumnToCompare) 
Select 'BBB87 BBB' 
Union all 
Select 'J97B B' 
union all 
select '282 8289' 
union all 
select 'UW83 7YY' 
union all 
select 'UW83 7Y0' 

Insert Into @patterns 
Select 'A9 9AA', 'A99AA' 
union all 
Select 'A99 9AA', 'A999AA' 
union all 
Select 'A9A 9AA', 'A9A9AA' 
union all 
Select 'AA9 9AA', 'AA99AA' 
union all 
Select 'AA99 9AA', 'AA999AA' 
union all 
Select 'AA9A 9AA', 'AA9A9AA' 


Update @table 
Set AmendedValue = Left(Replace(ColumnToCompare, ' ',''), (CharIndex(' ', Pattern)-1)) + space(1) + 
        SubString(Replace(ColumnToCompare, ' ',''), (CharIndex(' ', Pattern)), (Len(ColumnToCompare) - (CharIndex(' ', Pattern)-1))) 
From @table 
Cross Join @Patterns 
Where PatIndex(Replace((Replace(TrimmedPattern, 'A','[A-Z]')), '9','[0-9]'), Replace(ColumnToCompare, ' ' ,'')) > 0 

select * From @table 

這部分

Left(Replace(ColumnToCompare, ' ',''), (CharIndex(' ', Pattern)-1))

發現在已經匹配的模式空間,並採取串的左手部分進行比較。

它,然後添加一個空格

+ space(1) +

那麼這部分

SubString(Replace(ColumnToCompare, ' ',''), (CharIndex(' ', Pattern)), (Len(ColumnToCompare) - (CharIndex(' ', Pattern)-1)))

追加字符串爲新值的剩餘部分。