需求:表的某个字段数据是使用富文本编辑器保存的,其保存内容为html格式。现做报表只需要得到文字内容。因此写了一个sql方法来去除html标签,只保留文字内容。
sql方法如下:
GO
/****** Object: UserDefinedFunction [dbo].[myRemoveHtml] Script Date: 2020-05-21 16:14:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[myRemoveHtml] ( @str varchar(MAX) )
RETURNS varchar(MAX)
AS
BEGIN
--判断是否有标签
declare @int int
declare @nextx int
declare @nextd int
set @int = 1
WHILE CHARINDEX('<', @str,@int) > 0
--去除标签
begin
set @int = CHARINDEX('<', @str,@int)
set @nextx =CHARINDEX('<', @str,@int+1)
set @nextd =CHARINDEX('>', @str,@int+1)
if @nextd>@int
begin
if @nextx = 0
begin
SET @str = STUFF(@str, CHARINDEX('<', @str,@int),CHARINDEX('>', @str,@int) - CHARINDEX('<', @str,@int) + 1,'')
end
else
begin
if @nextx > @nextd
begin
SET @str = STUFF(@str, CHARINDEX('<', @str,@int),CHARINDEX('>', @str,@int) - CHARINDEX('<', @str,@int) + 1,'')
end
else
set @int = @nextx
end
end
else
set @int = @int +1
end
--去除空格
RETURN REPLACE(@str,' ','');
END
GO
方法实现原理:依次遍历"<",得到首个”<"的位置@int,然后得到下一个“<"和下一个”>“的位置@nextx和@nextd。比较@int和@nextx、@nextd,然后判断是否去除”<"和“>"之间的内容,并更新@int指针位置。
遍历完整个字符串后,就去除掉了html标签。最后再替换掉html空格字符串。
此方法的优点:不受文本内容中的大于符号和小于符号的影响。
参考博客:https://blog.csdn.net/qq_25037705/article/details/82106938 ,该博客的方法能去除掉html标签,但是遇到文本内容包含大于小于符号会失效。