这给出了你所需要的。首先创建功能。我正在使用您的数据作为示例。
CREATE FUNCTION [dbo].[RegexReplace]
(
@pattern VARCHAR(255),
@replacement VARCHAR(255),
@Subject VARCHAR(4000),
@global BIT = 1,
@Multiline bit =1
)
RETURNS VARCHAR(4000)
/*MORE DETAILS @ http://www.simple-talk.com/sql/t-sql-programming/tsql-regular-expression- workbench/ */
AS BEGIN
DECLARE @objRegexExp INT,
@objErrorObject INT,
@strErrorMessage VARCHAR(255),
@Substituted VARCHAR(8000),
@hr INT,
@Replace BIT
SELECT @strErrorMessage = 'creating a regex object'
EXEC @hr= sp_OACreate 'VBScript.RegExp', @objRegexExp OUT
IF @hr = 0
SELECT @strErrorMessage = 'Setting the Regex pattern',
@objErrorObject = @objRegexExp
IF @hr = 0
EXEC @hr= sp_OASetProperty @objRegexExp, 'Pattern', @pattern
IF @hr = 0 /*By default, the regular expression is case sensitive. Set the IgnoreCase property to True to make it case insensitive.*/
SELECT @strErrorMessage = 'Specifying the type of match'
IF @hr = 0
EXEC @hr= sp_OASetProperty @objRegexExp, 'IgnoreCase', 0
IF @hr = 0
EXEC @hr= sp_OASetProperty @objRegexExp, 'MultiLine', @Multiline
IF @hr = 0
EXEC @hr= sp_OASetProperty @objRegexExp, 'Global', @global
IF @hr = 0
SELECT @strErrorMessage = 'Doing a Replacement'
IF @hr = 0
EXEC @hr= sp_OAMethod @objRegexExp, 'Replace', @Substituted OUT,
@subject, @Replacement
/*If the RegExp.Global property is False (the default), Replace will return the @subject string with the first regex match (if any) substituted with the replacement text. If RegExp.Global is true, the @Subject string will be returned with all matches replaced.*/
IF @hr <> 0
BEGIN
DECLARE @Source VARCHAR(255),
@Description VARCHAR(255),
@Helpfile VARCHAR(255),
@HelpID INT
EXECUTE sp_OAGetErrorInfo @objErrorObject, @source OUTPUT,
@Description OUTPUT, @Helpfile OUTPUT, @HelpID OUTPUT
SELECT @strErrorMessage = 'Error whilst '
+ COALESCE(@strErrorMessage, 'doing something') + ', '
+ COALESCE(@Description, '')
RETURN @strErrorMessage
END
EXEC sp_OADestroy @objRegexExp
RETURN @Substituted
END
--EXAMPLE
DECLARE @YourLink AS VARCHAR(1000)
SELECT @YourLink = '<a href="_UpInclude/scriptEx/__TQinfoBaseImage.asp? rq_RecordId=28177&rq_MasterId=28177&rq_Revision=1">Link1</a>'
SELECT '<a href="/ror/current/' +
dbo.RegexReplace('.*__TQinfoBaseImage.asp?.*rq_MasterId=(\d+).*', '$1',@YourLink,1,1)
+ '.image">'
+ dbo.RegexReplace('<a\b[^>]*>(.*?)</ ?a>', '$1',@YourLink,1,1)
+ '</a>'
/*替换@YourLink随着数据山坳名得到的结果和更新*/
当我更改@主题和@代替varchar(MAX)它不再工作。来自源链接的版本我也试过,并且根本不工作。任何想法?目前它将我的内容限制为4000个字符,但我的内容有更多的字符。如果我在内容中有更多的链接,会发生什么情况?它是否会取代两者? – YvesR 2012-03-09 08:12:40
您可以制作'@Subject VARCHAR(max)'和'RETURN VARCHAR(max)'。如果你能找到正确的正则表达式函数将替换多个链接。例如'SELECT dbo.RegexReplace('?\w+\s+[^>] *>','',@ YourLink,1,1)'但是这不能找到您正在搜索的组模式。只查找锚的第一部分' –
Kaf
2012-03-09 10:16:10