【ZT】SqlServer正则替换函数 from 阿三

create function dbo.regexreplace
(
    @source ntext, --原字符串
    @regexp varchar(1000), --正则表达式
    @replace varchar(1000), --替换值
    @globalreplace bit = 1, --是否是全局替换
    @ignorecase bit = 0 --是否忽略大小写
)
returns varchar(1000) as
begin
    declare @hr integer
    declare @objregexp integer
    declare @result varchar(5000)

    exec @hr = sp_oacreate 'vbscript.regexp', @objregexp output
    if @hr <> 0 begin
        exec @hr = sp_oadestroy @objregexp
        return null
    end
    exec @hr = sp_oasetproperty @objregexp, 'pattern', @regexp
    if @hr <> 0 begin
        exec @hr = sp_oadestroy @objregexp
        return null
    end
    exec @hr = sp_oasetproperty @objregexp, 'global', @globalreplace
    if @hr <> 0 begin
        exec @hr = sp_oadestroy @objregexp
        return null
    end
    exec @hr = sp_oasetproperty @objregexp, 'ignorecase', @ignorecase
    if @hr <> 0 begin
        exec @hr = sp_oadestroy @objregexp
        return null
    end
    exec @hr = sp_oamethod @objregexp, 'replace', @result output, @source, @replace
    if @hr <> 0 begin
        exec @hr = sp_oadestroy @objregexp
        return null
    end
    exec @hr = sp_oadestroy @objregexp
        if @hr <> 0 begin
        return null
    end

    return @result
end
go

 使用上述存储过程需开启配置如下:

--开启 Ole Automation Procedures
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'Ole Automation Procedures';
GO

 

posted @ 2017-07-14 11:28  欧迪。  阅读(282)  评论(0)    收藏  举报