Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / SQL

Excluding HTML tags from query

5.00/5 (1 vote)
14 Aug 2013CPOL 14.2K  
Sql query for remove html tag from sql table field

Introduction

Sometimes we are inserting text with HTML-tag into a SQL Server database. But what to do if we need to execute a SQL query with Like clause on text only (without HTML tags)? Here we have to exclude HTML tags from the text then we can execute Like clause query on it. So here I'm going to show a SQL Scalar function for the same.

One user has the same requirement here: http://www.codeproject.com/Questions/536178/Excluding-html-tags-from-query and it is solved by this code snippet.

Using the code   

If we have added "Test Testimonial" it stores in database as '<p>Test Testimonial</p>" and while showing in grid it shows "Test Testimonial". If I want to run a query like "select Testimonial from Testimonials where Testimonial like 'T%' " it shows no result.

The function is here:

SQL
CREATE FUNCTION RemoveHtmlString
(
    -- 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
GO

Then execute your query as

SQL
select Testimonial  from Testimonials  where dbo.RemoveHtmlString(Testimonial)   like 'T%'

The function will remove HTML tags from the field before executing the like clause.

History 

Please let me know if someone has an easier way than this.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)