create FUNCTION dbo.fn_UrlEncode_V2(@Str nvarchar(max))
RETURNS nvarchar(max)
AS
BEGIN
DECLARE @RtnValue nvarchar(max)
set @Str = REPLACE(@Str, ' ', '')
SELECT @RtnValue = replace28
FROM (
SELECT @Str AS DataValue
) AS A
cross apply (SELECT replace0_1 = REPLACE(A.DataValue, CHAR(13) + CHAR(10), '')) r0_1
cross apply (SELECT replace0_2 = REPLACE(replace0_1, CHAR(13), '')) r0_2
cross apply (SELECT replace0 = REPLACE(replace0_2, CHAR(10), '')) r0
cross apply (SELECT replace1 = REPLACE(replace0, '%', '%25')) r1
cross apply (SELECT replace2 = REPLACE(replace1, '&', '%26')) r2
cross apply (SELECT replace3 = REPLACE(replace2, '$', '%24')) r3
cross apply (SELECT replace4 = REPLACE(replace3, '+', '%2B')) r4
cross apply (SELECT replace5 = REPLACE(replace4, ',', '%2C')) r5
cross apply (SELECT replace6 = REPLACE(replace5, ':', '%3A')) r6
cross apply (SELECT replace7 = REPLACE(replace6, ';', '%3B')) r7
cross apply (SELECT replace8 = REPLACE(replace7, '=', '%3D')) r8
cross apply (SELECT replace9 = REPLACE(replace8, '?', '%3F')) r9
cross apply (SELECT replace10 = REPLACE(replace9, '@', '%40')) r10
cross apply (SELECT replace11 = REPLACE(replace10, '#', '%23')) r11
cross apply (SELECT replace12 = REPLACE(replace11, '<', '%3C')) r12
cross apply (SELECT replace13 = REPLACE(replace12, '>', '%3E')) r13
cross apply (SELECT replace14 = REPLACE(replace13, '[', '%5B')) r14
cross apply (SELECT replace15 = REPLACE(replace14, ']', '%5D')) r15
cross apply (SELECT replace16 = REPLACE(replace15, '{', '%7B')) r16
cross apply (SELECT replace17 = REPLACE(replace16, '}', '%7D')) r17
cross apply (SELECT replace18 = REPLACE(replace17, '|', '%7C')) r18
cross apply (SELECT replace19 = REPLACE(replace18, '^', '%5E')) r19
cross apply (SELECT replace20 = REPLACE(replace19, ' ', '%20')) r20
cross apply (SELECT replace21 = REPLACE(replace20, '~', '%7E')) r21
cross apply (SELECT replace22 = REPLACE(replace21, '`', '%60')) r22
cross apply (SELECT replace23 = REPLACE(replace22, '*', '%2A')) r23
cross apply (SELECT replace24 = REPLACE(replace23, '(', '%28')) r24
cross apply (SELECT replace25 = REPLACE(replace24, ')', '%29')) r25
cross apply (SELECT replace26 = REPLACE(replace25, '/', '%2F')) r26
cross apply (SELECT replace27 = REPLACE(replace26, '\', '%5C')) r27
cross apply (SELECT replace28 = REPLACE(replace27, ' ', '%20')) r28
SET @RtnValue = REPLACE(@RtnValue, '"', '%22')
SET @RtnValue = REPLACE(@RtnValue, CHAR(13), '')
SET @RtnValue = REPLACE(@RtnValue, CHAR(10), '')
SET @RtnValue = REPLACE(@RtnValue, ' ', '') -- tab
RETURN @RtnValue
END