Labels

Wednesday, May 4, 2011

How to remove HTML Tags?

--Step 1: Table Created:
CREATE TABLE [dbo].MainTable(
      [HTMLCode] [varchar](50) NULL,
      [PlainText] [varchar](40) NULL
)
GO

--Step 2: Records Inserted:
INSERT [dbo].MainTable ( [HTMLCode], [PlainText]) VALUES ( '<B>HEAD</B>', 'Vinod')
INSERT [dbo].MainTable ( [HTMLCode], [PlainText]) VALUES ( '<B>Title</B>', 'Amit')
INSERT [dbo].MainTable ( [HTMLCode], [PlainText]) VALUES ( '<B>Body</B>', 'Sagar')
INSERT [dbo].MainTable ( [HTMLCode], [PlainText]) VALUES ( '<I>TD</I>', 'Atul')
INSERT [dbo].MainTable ( [HTMLCode], [PlainText]) VALUES ( '<I>TH</I>', 'Rajesh')
INSERT [dbo].MainTable ( [HTMLCode], [PlainText]) VALUES ( '<B><I>TR</I></B>', 'Rahul')
GO
--Step 3: Function Created:
Create Function [dbo].[fnRemoveHtmlTags]
    (@Dirty varchar(4000))
    Returns varchar(4000)
As
Begin
    Declare @Start int,
        @End int,
        @Length int
    While CharIndex('<', @Dirty) > 0 And CharIndex('>', @Dirty) > 0
        Begin
        Select @Start = CharIndex('<', @Dirty),
          @End = CharIndex('>', @Dirty)
        Select @Length = (@End - @Start) + 1
        If @Length > 0
            Begin
            Select @Dirty = Stuff(@Dirty, @Start, @Length, '')
            End
        End
    return @Dirty
End
Go
--Step 4: How to use:
SELECT ID, [DBO].[FNSTRIPTAGS](HTMLCODE), PLAINTEXT FROM MainTable

-- The one more way to check
declare @str varchar(299)
select @str = '<B><I>TR</I>M</B>'
select cast (@str as xml).query('.').value('.', 'varchar(200)')

No comments:

Post a Comment