SQL 正則表達式使用

    --====================================  
    --標題: 應用實例之SQL SERVER 正則匹配  
    --作者:maco_wang  
    --時間:2012-03-25  
    --說明:MS-SQL SERVER 中的正則匹配  
    --====================================  
      
    /*  
    假設測試數據爲:  
    col  
    ----------  
    a b d c e  
    a a b c d  
    b b c d e  
    e u g h w  
    o a k d w  
      
    1)得到沒有重複字母的行,即想要得到如下結果:  
    col  
    --------------  
    a b c d e  
    e u g h w  
    o p k n w  
      
    2)得到同時存在a和d,並且a和d之間只有0或是1個字母的,即想要得到的結果:  
    col  
    ----------  
    a b d c e  
    o a k d w  
      
    */  
      
    --測試數據  
    if object_id('[tb]') is not null drop table [tb]  
    create table [tb] (col varchar(10))  
    insert into [tb]  
    select 'a b d c e' union all  
    select 'a a b c d' union all  
    select 'b b c d e' union all  
    select 'e u g h w' union all  
    select 'o a k d w'   
      
    select * from [tb]  
      
    --本示例在SQL SERVER 2000版本即可適用。  
      
    go  
    create function dbo.RegexMatch  
    (  
        @pattern varchar(2000),  
        @matchstring varchar(8000)  
    )  
    returns int  
    as   
    begin  
        declare @objRegexExp int  
        declare @strErrorMessage varchar(255)  
        declare @hr int,@match bit  
        exec @hr= sp_OACreate 'VBScript.RegExp', @objRegexExp out  
        if @hr = 0   
            exec @hr= sp_OASetProperty @objRegexExp, 'Pattern', @pattern  
        if @hr = 0   
            exec @hr= sp_OASetProperty @objRegexExp, 'IgnoreCase', 1  
        if @hr = 0   
            exec @hr= sp_OAMethod @objRegexExp, 'Test', @match OUT, @matchstring  
        if @hr <>0   
        begin  
            return null  
        end  
        exec sp_OADestroy @objRegexExp  
        return @match  
    end  
      
    go  
    --1)得到沒有重複字母的行  
    --正常思路,可能是按照空格分割後去重然後合併,最後判斷長度(略)  
      
    --用正則就很方便了  
    select col from [tb] where dbo.RegexMatch('^.*?([a-z])[ ]\1.*?$',col)=0  
    /*  
    col  
    ----------  
    a b d c e  
    e u g h w  
    o a k d w  
    */  
      
    --2)得到同時存在a和d,並且a和d之間間隔小於等於一個字母的  
      
    --正常思路  
    select col from [tb]   
    where charindex('a',col)>0  
    and charindex('d',col)>0  
    and abs(charindex('a',col)-charindex('d',col))<5  
    /*  
    col  
    ----------  
    a b d c e  
    o a k d w  
    */  
    --正則處理  
    select col from [tb] where dbo.RegexMatch('.*a[a-z ]{1,3}d.*',col)=1  
    /*  
    col  
    ----------  
    a b d c e  
    o a k d w  
    */  
    --這裏的正則寫法考慮的就不全,如果d在a前面呢?  
    --那麼修正一下  
    select col from [tb]   
    where dbo.RegexMatch('.*d[a-z ]{1,3}a.*|.*a[a-z ]{1,3}d.*',col)=1  
    /*  
    col  
    ----------  
    a b d c e  
    o a k d w  
    */  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章