SQL Function to Strip HTML from a field

Create function SS_StripHTML(@html varchar(max)) returns varchar(max)

as

Begin

declare @p int

declare @nonspace bit

declare @istag bit

declare @chr varchar(1)

declare @result varchar(max)

set @p=1

set @istag=0

set @result=''

set @nonspace=0

set @html=replace(@html,char(13)+char(10),'')

set @html=replace(@html,'<br>','{&&BR&&}')

while @p<len(@html)

begin

set @chr=substring(@html,@p,1)

if @chr='<' set @istag=1

if @chr='>'

begin

set @istag=0

set @nonspace=0

end

else

begin

if ascii(@chr)>32 set @nonspace=1

if @istag=0 and @nonspace=1 set @result=@result+@chr

end

set @p=@p+1

end

set @result=replace(@result,'&nbs'+'p;',' ');

set @result=replace(@result,'&am'+'p;','&');

set @result=replace(@result,'&l'+'t;','<');

set @result=replace(@result,'&g'+'t;','>');

set @result=replace(@result,'&quo'+'t;','"');

set @result=replace(@result,'{&&BR&&}',char(13)+char(10));

return @result

end