Remove HTML Tags

| |

This script will remove all HTML tags from a given column in a table, useful if you need to simply have the text.

IF OBJECT_ID(N'dbo.RemoveHTMLTags') IS NOT NULL
	DROP FUNCTION dbo.RemoveHTMLTags
GO

CREATE FUNCTION [dbo].[RemoveHTMLTags] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
	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

Source: http://blog.sqlauthority.com/2007/06/16/sql-server-udf-user-defined-function-to-strip-html-parse-html-no-regular-expression/

Originally Posted on October 23, 2013
Last Updated on October 26, 2015
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.