SQL Server中利用正则表达式替换字符串的方法

栏目: 数据库 · SQL Server · 发布时间: 8年前

内容简介:这篇文章主要介绍了SQL Server中利用正则表达式替换字符串的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下

建立正则替换函数,利用了OLE对象,以下是函数代码:

--如果存在则删除原有函数 
IF OBJECT_ID(N'dbo.RegexReplace') IS NOT NULL 
 DROP FUNCTION dbo.RegexReplace 
GO 
--开始创建正则替换函数 
 CREATE FUNCTION dbo.RegexReplace 
( 
 @string VARCHAR(MAX), --被替换的字符串 
 @pattern VARCHAR(255), --替换模板 
 @replacestr VARCHAR(255), --替换后的字符串 
 @IgnoreCase INT = 0 --0区分大小写 1不区分大小写 
) 
RETURNS VARCHAR(8000) 
AS 
BEGIN 
 DECLARE @objRegex INT, @retstr VARCHAR(8000) 
 --创建对象 
 EXEC sp_OACreate 'VBScript.RegExp', @objRegex OUT 
 --设置属性 
 EXEC sp_OASetProperty @objRegex, 'Pattern', @pattern 
 EXEC sp_OASetProperty @objRegex, 'IgnoreCase', @IgnoreCase 
 EXEC sp_OASetProperty @objRegex, 'Global', 1 
 --执行 
 EXEC sp_OAMethod @objRegex, 'Replace', @retstr OUT, @string, @replacestr 
 --释放 
 EXECUTE sp_OADestroy @objRegex 
 RETURN @retstr 
END 
GO 
--保证正常运行的话,需要将Ole Automation Procedures选项置为1 
EXEC sp_configure 'show advanced options', 1 
RECONFIGURE WITH OVERRIDE 
EXEC sp_configure 'Ole Automation Procedures', 1 
RECONFIGURE WITH OVERRIDE 



--2.将姓名倒过来 
SELECT dbo.RegexReplace('John Smith', '([a-z]+)\s([a-z]+)', '$2,$1',1) 
/* 
-------------------------------------- 
Smith,John 
*/ 
--------------------------------------------------

只有对写程序充满热情,才能写出好的程序!


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pattern Recognition and Machine Learning

Pattern Recognition and Machine Learning

Christopher Bishop / Springer / 2007-10-1 / USD 94.95

The dramatic growth in practical applications for machine learning over the last ten years has been accompanied by many important developments in the underlying algorithms and techniques. For example,......一起来看看 《Pattern Recognition and Machine Learning》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

URL 编码/解码
URL 编码/解码

URL 编码/解码

SHA 加密
SHA 加密

SHA 加密工具