marty001 发表于 2017-7-13 20:52:58

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

  博客原文来源:http://blog.csdn.net/return_false/article/details/11984613




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
)
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
EXEC sp_configure 'show advanced options', 1   
RECONFIGURE WITH OVERRIDE   
EXEC sp_configure 'Ole Automation Procedures', 1   
RECONFIGURE WITH OVERRIDE   
  复制以上代码,到SQL中执行
  然后测试,如下




SELECT dbo.RegexReplace('John Smith', '(+)\s(+)', '$2,$1',1)   
   
      
  在自己的项目中测试:查询结果去掉html标签



Select dbo.RegexReplace('<p><span>(1)您手脚发凉吗?</span><br/></p>','\<[^<>]*\>','',1)
  结果:
页: [1]
查看完整版本: SQL Server中利用正则表达式替换字符串