Home » Programming / Coding, Technology

Strip HTML Tags – MS SQL

15 March 2010 794 views No Comment

Here is a UDF (user defined function) to strip off html tags from a string in MS SQL.

CREATE FUNCTION [dbo].[StripHtmlTags]
(
– Add the parameters for the function here
@HTMLText NVARCHAR(MAX)
)
RETURNS NVARCHAR(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

Example Use:

Execute StripHtmlTags('my <b>html filled</b> string');

Note: The use of MAX is allowed on MS SQL 2005 or newer versions of MS SQL servers. To use it with MS SQL versions older then 2005 (e.g. 2000) replace the MAX with a number for example 1500.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.