這給出了你所需要的。首先創建功能。我正在使用您的數據作爲示例。
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