String tsql子字符串或字符串操作

String tsql子字符串或字符串操作,string,tsql,substring,String,Tsql,Substring,我有一个nvarcharmax列,我需要提取开始a href标记和结束a 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

我有一个nvarcharmax列,我需要提取开始a href标记和结束a 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>"

任何帮助都将不胜感激

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


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


我同意为此使用CLR,但正则表达式不能可靠地用于解析html。为了更好地了解这一点,请看。。。cannot holdHTML是一种复杂程度足以让正则表达式无法解析的语言。即使Jon Skeet也不能使用常规表达式解析HTML,我同意,但作者不需要解析HTML。由于问题很简单,“提取开始a href标记和结束a href标记之间的所有内容”-KISS原则在这里应该可以正常工作。我不知道解析和提取之间的区别,但对于这种情况,正则表达式可能就足够了。我只是想提醒OP在使用正则表达式时可能遇到的问题。请注意,编写一个合适的正则表达式可能非常棘手,如果OP打算使用CLR,afaik.NET已经提供了可以解析HTML的库。我同意使用CLR来解析HTML,但正则表达式不能可靠地用于解析HTML。为了更好地了解这一点,请看。。。cannot holdHTML是一种复杂程度足以让正则表达式无法解析的语言。即使Jon Skeet也不能使用常规表达式解析HTML,我同意,但作者不需要解析HTML。由于问题很简单,“提取开始a href标记和结束a href标记之间的所有内容”-KISS原则在这里应该可以正常工作。我不知道解析和提取之间的区别,但对于这种情况,正则表达式可能就足够了。我只是想提醒OP在使用正则表达式时可能遇到的问题。请注意,编写一个合适的正则表达式可能非常棘手,如果OP打算使用CLR,afaik.NET已经提供了可以解析HTML的库。
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