SQL Server replacement function application

Source: Internet
Author: User
Tags integer microsoft sql server ole regular expression

--sql Regular Replace function

The

Code is as follows:
CREATE function Dbo.regexreplace
(
@source ntext, the original string
@regexp varchar (1000),--Regular expression
@rep Lace varchar (1000),--Replaces the value
@globalReplace bit = 1, whether it is global replace
@ignoreCase bit = 0-Ignore case
)
ReturnS varcha R (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 br> 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< br> 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

/*
Configuring support for extended stored procedures
Microsoft SQL Server-> Configuration Tool-> Perimeter application configuration-> configuration-> OLE Automation: Support for OLE Automation

Use Example 1:
The code is as follows:
declare @source nvarchar (4000)
Set @source = ' Dsafsdf '
Select Dbo.regexreplace (@source, ' <[^>]+> ', ', ', 1, 1)

Use Example 2: (The database field contains <font color= ' #ff0000 ' >aaa</font> replace with <font>aaa</font>)
Select id,dbo.regexreplace (field, ' <font ([^>]) *> ', ' <font> ', 1,0) as Alias from table
*/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.