TSQL Function to encode HTML Text
This post was written by namwar on January 20, 2009
Posted Under: How-To, TSQL, Tips, Utility Functions
Posted Under: How-To, TSQL, Tips, Utility Functions
While browsing through the Sharepoint content database, I found a very useful TSQL utility function which can be used in any application. This function encodes the given html so that it can be safely used in XML tags and other html rendering requirements.
Please note, this function is originally provided in Sharepoint content database and I have just copied it because of its usefulness. PLEASE DO NOT CALL it directly from Sharepoint database as it is not recommended and supported by Microsoft. Just create this function in your own database and modify it as per your requirement.
set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go CREATE FUNCTION [dbo].[fn_HtmlEncode]( @Value nvarchar(1023), @PreserveNewLine bit) RETURNS nvarchar(4000) AS BEGIN DECLARE @Result nvarchar(4000) SELECT @Result = @Value IF @Result IS NOT NULL AND LEN(@Result) > 0 BEGIN SELECT @Result = REPLACE(@Result, N'&', N'&') SELECT @Result = REPLACE(@Result, N'<', N'<') SELECT @Result = REPLACE(@Result, N'>', N'>') SELECT @Result = REPLACE(@Result, N'''', N''') SELECT @Result = REPLACE(@Result, N'"', N'"') IF @PreserveNewLine = 1 SELECT @Result = REPLACE(@Result, CHAR(10), CHAR(10) + N'<br>') END RETURN @Result END




