Skip to main content

SQL Server function to strip HTML tags.

-- https://blog.sqlauthority.com/2007/06/16/sql-server-udf-user-defined-function-to-strip-html-parse-html-no-regular-expression/
create function dbo.udf_StripHtmlTags
(
    @HtmlText nvarchar(max)
)
returns nvarchar(max)
as
begin
    if @HtmlText is null
    begin
        return null;
    end;

    declare @start int;
    declare @end int;
    declare @length int;

    set @start = charindex('<', @HtmlText);
    set @end = charindex('>', @HtmlText, charindex('<', @HtmlText));
    set @length = (@end - @start) + 1;

    while @start > 0 and @end > 0 and @length > 0
    begin
        set @HtmlText = stuff(@HtmlText, @start, @length, '');
        set @start = charindex('<', @HtmlText);
        set @end = charindex('>', @HtmlText, charindex('<', @HtmlText));
        set @length = (@end - @start) + 1;
    end;

    return ltrim(rtrim(@HtmlText));
end;
go