-->

TSQL Function to encode HTML Text

Post a Comment

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'&#39;')
		 SELECT @Result = REPLACE(@Result, N'"', N'&quot;')
		 IF @PreserveNewLine = 1 
			SELECT  @Result = REPLACE(@Result, CHAR(10), CHAR(10) + N'<br>')
	END
    RETURN @Result
END

Related Posts

There is no other posts in this category.

Post a Comment

Subscribe Our Newsletter