ALTER FUNCTION [dbo].[str_htmlEncode] ( @UnEncoded as varchar(max) ) RETURNS varchar(max) AS BEGIN DECLARE @Encoded as varchar(max) --order is important here. Replace the amp first, then the lt and gt. --otherwise the < will become &lt; SELECT @Encoded = Replace( Replace( Replace(@UnEncoded,'&','&'), '<', '<'), '>', '>') RETURN @Encoded END