SQL替换URL通配符

时间:2016-01-26 08:38:17

标签: sql sql-server tsql sql-server-2012

我需要匹配sql中的所有记录并替换url匹配http://www.test.com/等的位置。我需要从标记的开头删除到结束标记。

For example content may have 
same data here <a href="http://www.test.com/personal/car-leasing/kia/pro ceed/" rel="nofollow" 
target="_blank"><img alt="Contract hire" src="/cms-images/car-hire.jpg" /></a> and here

我需要删除

这些链接的车型各不相同,但都以http://www.test.com/

开头

我尝试了以下但不确定如何在替换声明中逃脱

SELECT content, REPLACE(content, '<a href="http://www.test.com/%','') 
from cms.dbo.tblpost
where id = 47066

1 个答案:

答案 0 :(得分:0)

DECLARE @tblpost TABLE (
    ID INT NOT NULL IDENTITY PRIMARY KEY
    ,content NVARCHAR(MAX)
)

INSERT INTO @tblpost (content)
VALUES 
    (N'example www.test.com/personal')
    ,(N'example content may have same data here <a href="http://www.test.com/personal/car-leasing/kia/pro ceed/" rel="nofollow" 
target="_blank"><img alt="Contract hire" src="/cms-images/car-hire.jpg" /></a> and here')

DECLARE @Url NVARCHAR(4000) = N'www.test.com'
    ,@OpenTagRev NCHAR(2) = N'a<'       -- Reversed open tag <a href
    ,@CloseTag NCHAR(4) = N'</a>'

;WITH SearchUrl as (
    SELECT ID, content, CHARINDEX ( @Url ,content) UrlPos
    FROM @tblpost
)
, SearchOpenCloseTag as (
    SELECT ID, content, UrlPos, CHARINDEX(@OpenTagRev, REVERSE(LEFT(content, UrlPos))) OpenTagOffset, CHARINDEX ( @CloseTag ,content, UrlPos) CloseTagPos
    FROM SearchUrl
    WHERE UrlPos > 0
)

SELECT ID, content, STUFF(content, UrlPos - OpenTagOffset, CloseTagPos - UrlPos + OpenTagOffset + 4 /* 4 IS LEN(@CloseTag) */, N'') ReplContent
FROM SearchOpenCloseTag
WHERE OpenTagOffset > 0
    AND CloseTagPos > 0