T-SQL字符串操作,替换,比较,模式匹配,正则表达式

时间:2011-11-16 12:04:16

标签: sql-server regex sql-server-2005

我有一小串字母数字字符A-Z和0-9

字符和数字都包含在字符串中。

我想剥离空格,并将每个字符串与只与其匹配的“模式”进行比较。模式使用A来表示任何0-9的任何字符A-Z和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')

基本上,我试图通过一个愚蠢的方式在呼叫中心输入英国邮政编码,并将输入的邮政编码与上述6种模式中的一种进行模式匹配,并找出插入空间的位置。

1 个答案:

答案 0 :(得分: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)))

将字符串的其余部分附加到新值。