Click here to Skip to main content
15,913,941 members
Articles / Programming Languages / SQL
Tip/Trick

Excluding HTML tags from query

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
14 Aug 2013CPOL 14K   3   1
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)


Written By
Software Developer BHARTI Airtel
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionthank you Pin
Nur Maulidiyah4-Dec-14 21:21
Nur Maulidiyah4-Dec-14 21:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.