Looking for a bug free tested sql script that i could use in a UDF to encode a url through sql. Function would take in a URL and pass out a URL Encoded URL. I have seen a few,
Daniel Hutmacher from SQL Sunday has provided a nice function.
https://sqlsunday.com/2013/04/07/url-encoding-function/
CREATE FUNCTION dbo.fn_char2hex(@char char(1))
RETURNS char(2)
AS BEGIN
DECLARE @hex char(2), @dec int;
SET @dec=ASCII(@char);
SET @hex= --- First hex digit:
SUBSTRING('0123456789ABCDEF', 1+(@dec-@dec%16)/16, 1)+
--- Second hex digit:
SUBSTRING('0123456789ABCDEF', 1+( @dec%16) , 1);
RETURN(@hex);
END
CREATE FUNCTION dbo.fn_UrlEncode(@string varchar(max))
RETURNS varchar(max)
AS BEGIN
DECLARE @offset int, @char char(1);
SET @string = REPLACE(@string, '%', '%' + dbo.fn_Char2Hex('%'));
SET @offset=PATINDEX('%[^A-Z0-9.\-\%]%', @string);
WHILE (@offset!=0) BEGIN;
SET @char = SUBSTRING(@string, @offset, 1);
SET @string = REPLACE(@string, @char, '%' + dbo.fn_Char2Hex(@char));
SET @offset = PATINDEX('%[^A-Z0-9.\-\%]%', @string);
END
RETURN @string;
END;