Call now: (800) 766-1884  


 SQL Server Tips
 SQL Server Training

 SQL Server Consulting
 SQL Server Support
 SQL Server Remote DBA

 SQL Server Scripts
 Scripts Menu




  SQL Server Tips by Gama and Naughter

Applications of XP_HTMLENCODE

A function equivalent to XP_HTMLENCODE can be implemented with an UDF containing several REPLACE calls but there might be a problem if the UDF will work with both ASCII and Unicode input. The problem is that the input parameter must have a specific data type, in this case either varchar or nvarchar but if the input is Unicode and the parameter is ASCII there might be loss of data for all the characters that cannot be mapped; if the input is ASCII and the parameter is unicode there might be data loss too because the data will be truncated over the first 4000 characters. One workaround is to use two functions, one for ASCII and the other one for Unicode with the same code but different data types for input and output. A better solution is to use sql_variant variables and an IF statement to execute the code for ASCII or Unicode, depending on the input. There is still the overhead caused by using sql_variant and it gets worse as the code gets more extensive and complex.

--UDF that emulates HTMLENCODE
RETURNS sql_variant
DECLARE @output_variant sql_variant
IF SQL_VARIANT_PROPERTY(@input,'BaseType') IN ('nvarchar', 'nchar')
DECLARE @output1 nvarchar(4000)
SET @output1=CONVERT(nvarchar(4000), @input)
SET @output1=REPLACE(@output1,N'&', N'&')
SET @output1=REPLACE(@output1,N'>', N'>')
SET @output1=REPLACE(@output1,N'<', N'&lt;')
SET @output1=REPLACE(@output1,N'''', N'&apos;')
SET @output1=REPLACE(@output1,N'"', N'&quot;')
SET @output_variant=@output1
DECLARE @output2 varchar(8000)
SET @output2=CONVERT(varchar(8000), @input)
SET @output2=REPLACE(@output2,'&', '&amp;')
SET @output2=REPLACE(@output2,'>', '&gt;')
SET @output2=REPLACE(@output2,'<', '&lt;')
SET @output2=REPLACE(@output2,'''', '&apos;')
SET @output2=REPLACE(@output2,'"', '&quot;')
SET @output_variant=@output2
RETURN @output_variant

The above book excerpt is from:

Super SQL Server Systems
Turbocharge Database Performance with C++ External Procedures

ISBN: 0-9761573-2-2
Joseph Gama, P. J. Naughter  


Burleson Consulting Remote DB Administration







Burleson is the America's Team

Note: The pages on this site were created as a support and training reference for use by our staff of DBA consultants.  If you find it confusing, please exit this page.

Errata?  SQL Server technology is changing and we strive to update our SQL Server support information.  If you find an error or have a suggestion for improving our content, we would appreciate your feedback.  Just  e-mail:and include the URL for the page.

Burleson Consulting
SQL Server database support


Copyright 1996 -  2013 by Vaaltech Web Services. All rights reserved.

Hit Counter