TSQL - How to URL Encode

前端 未结 5 1917
清酒与你
清酒与你 2021-02-13 11:22

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,

5条回答
  •  误落风尘
    2021-02-13 11:33

    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;
    

提交回复
热议问题