2011-11-16 47 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)))

追加字符串为新值的剩余部分。