|
 |
|
SQL Server Tips by Burleson |
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.
CREATE FUNCTION UDFHTMLENCODE(@input
sql_variant)
--UDF that emulates HTMLENCODE
RETURNS sql_variant
AS
BEGIN
DECLARE @output_variant sql_variant
IF SQL_VARIANT_PROPERTY(@input,'BaseType') IN ('nvarchar', 'nchar')
BEGIN
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'<')
SET @output1=REPLACE(@output1,N'''', N''')
SET @output1=REPLACE(@output1,N'"', N'"')
SET @output_variant=@output1
END
ELSE
BEGIN
DECLARE @output2 varchar(8000)
SET @output2=CONVERT(varchar(8000), @input)
SET @output2=REPLACE(@output2,'&', '&')
SET @output2=REPLACE(@output2,'>', '>')
SET @output2=REPLACE(@output2,'<', '<')
SET @output2=REPLACE(@output2,'''', ''')
SET @output2=REPLACE(@output2,'"', '"')
SET @output_variant=@output2
END
RETURN @output_variant
END
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
http://www.rampant-books.com/book_2005_2_sql_server_external_procedures.htm |