2010-03-10 88 views
1

对于正则表达式我不太了解,我想根据流动指令尝试解析数据库中的sting。 我知道我需要使用CLR但开始我想学习正则表达式MS SQL中的正则表达式

表中数据的样子

create table #tempTBL (opis varchar(40)) 
go 
insert into #tempTBL 
select 'C 136' 
union 
select 'C 145' 
union 
select 'C146' 
union 
select 'AK C 182' 
union 
select 'C 277' 
union 
select 'C-240' 
union 
select 'ISPRAVKA PO C 241' 

,并选择刺看起来像

Select 
    reverse(
      rtrim(
        ltrim(
          replace(
            (substring 
              (reverse(opis) 
                ,0 
                ,charindex(
                   'C',reverse(opis) 
                   ) 
              ) 
            ) 
          ,'-',' ') 
         ) 
       ) 
      ) as jci 
from #tempTBL 

应该如何看起来像我的C#代码重复使用正则表达式

回答

1

与构建CLR程序集以应用正则表达式以满足此特定要求相比,您可能更适合构建一组通用正则表达式CLR函数。

有许多例子在那里,但this article是好的开始任何

编辑的地方 如果您的例子涵盖了全方位的数据可能配置,需要可能是正则表达式像(\d+)(意味着作为匹配组返回的一个或多个连续数字)那样简单。

1

看到这article。它只需将一个.NET函数添加到sqlserver中,然后在查询中将其作为sqlserver函数调用。

1

使用CLR正则表达式可能会相当慢。如果转换过程与示例中一样简单,那么最好使用简单的SQL。

看看PATINDEX函数,它可能会有用。 另外,为了清晰起见,我建议将提取封装到UDF中。

create function dbo.ParseNum(@s varchar(40)) returns char(3) 
as begin 
    declare @n int 
    set @s = replace(replace(@s, '-', ''), ' ', '') 
    set @n = patindex('%C[0-9][0-9][0-9]', @s) 
    if @n = 0 return null 
    return substring(@s, @n+1, 3) 
end 
go 

select opis, dbo.ParseNum(opis) from #tempTBL