How to remove HTML tag using SQL?

If you have your data with tags like < div>,< span> , < br> , etc. You can use the function below to remove this characters from your string. Blog.

The function removes all content between the characteres < , > and also that characteres too.

Sample Data

HTMLString ClearString
< div>Age </ div> Age
< div> < span> Gender < span> </ div> Gender
< div>FirstName < br></ div> FirstName
< div> < strong>Surname </ strong> </ div> Surname

The HTMLString is the input for the function below, the column ClearString is the output for the function below.

Code

CREATE FUNCTION dbo.RemoveTag (@String VARCHAR(MAX))
RETURNS VARCHAR(MAX) AS
BEGIN
    DECLARE @Start INT
    DECLARE @End INT
    DECLARE @Length INT

SET @Start = CHARINDEX('&lt;',@String)
SET @End = CHARINDEX('&gt;',@String,CHARINDEX('&lt;',@String))
SET @Length = (@End - @Start) + 1

WHILE @Start &gt; 0 AND @End &gt; 0 AND @Length &gt; 0
    BEGIN
        SET @String = STUFF(@String,@Start,@Length,'')
        SET @Start = CHARINDEX('&lt;',@String)
        SET @End = CHARINDEX('&gt;',@String,CHARINDEX('&lt;',@String))
        SET @Length = (@End - @Start) + 1
    END

    RETURN LTRIM(RTRIM(@String))
END)

I hope that will help you.

Cheers!