您的位置:首页 > 数据库

[MSSQL]正则表达式在数据库编程中使用,其实真的不懂SQL了

2012-09-29 13:14 656 查看
一直以为单纯的查询分析数据表,基本上都OK。今天遇到一位朋友提出。

邮件地址字段,去掉163,sina,china

感觉很简单,不就是like not like in not math[],charindexof

发现会导致重复项,咋办呢?想了想,我们编程的时候有时候进行正则验证,SQL有没有类似的呢?

百度吧:

http://topic.csdn.net/u/20100415/17/4e3d9f41-5159-4b95-a52e-14f30b6f8ca9.html

发现这哥们的需求和我一样,但是貌似没人回答。

继续:终于发现新大陆了

/article/1415030.html

函数:

(  
    @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

测试成功,可是这个正则如何写呢?当时不好好学。

继续百度:http://www.yesky.com/imagesnew/software/vbscript/html/jsgrpRegExpSyntax.htm

(?!pattern)负向预查,在任何不匹配Negative lookahead matches the search string at any point where a string not matching
pattern 的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如'Windows (?!95|98|NT|2000)' 能匹配 "Windows 3.1" 中的 "Windows",但不能匹配 "Windows 2000" 中的 "Windows"。预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始
测试:

select col from [tb] where dbo.RegexMatch('(!|163|sina|china)',col)=0

结果没有问题通过测试。

SQL SERVER 2008 可能出现以下错误提示:

SQL Server 阻止了对组件 'Ole Automation Procedures' 的 过程'sys.sp_OACreate' 的访问

---开启配置

USE master;
GO
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

--查询配置信息

RECONFIGURE;
EXEC sp_configure;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: