tsql子串或字符串操作

时间:2011-09-30 05:52:22

标签: string tsql substring

我有一个nvarchar(max)列,我需要在打开href标签和关闭href标签之间提取所有内容。例如,如果我的列的内容如下:

Here you can visit <a href="http://www.thisite.com">this link</a> or this
<a href="http://www.newsite.com">new link</a>. this is just a test to find the right answer.

然后我的查询结果应为:

"<a href="http://www.thisite.com">this link</a>"
"<a href="http://www.newsite.com">new link</a>"

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

您必须使用CLR用户定义的函数(在Sql Server 2005 +中受支持):

Regular Expressions Make Pattern Matching And Data Extraction Easier

答案 1 :(得分:0)

declare @a varchar(max) = 'Here you can visit <a href="http://www.thisite.com">this link</a> or this <a href="http://www.newsite.com">new link</a>. this is just a test to find the right answer. '

;with cte as
(
select cast(1 as bigint) f, cast(1 as bigint) t 
union all 
select charindex('<a href=', @a, t), charindex('</a>', @a, charindex('<a href=', @a, t)) 
from cte where charindex('<a href=', @a, t) > 0
)
select substring(@a, f, t-f)+'</a>' from cte
where t > 1