TSQL - How to URL Encode

前端 未结 5 1921
清酒与你
清酒与你 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:29

    In order to use this script, you'll want to use Numbers table.

    CREATE FUNCTION [dbo].[URLEncode] 
        (@decodedString VARCHAR(4000))
    RETURNS VARCHAR(4000)
    AS
    BEGIN
    /******
    *       select dbo.URLEncode('K8%/fwO3L mEQ*.}')
    **/
    
    DECLARE @encodedString VARCHAR(4000)
    
    IF @decodedString LIKE '%[^a-zA-Z0-9*-.!_]%' ESCAPE '!'
    BEGIN
        SELECT @encodedString = REPLACE(
                                        COALESCE(@encodedString, @decodedString),
                                        SUBSTRING(@decodedString,num,1),
                                        '%' + SUBSTRING(master.dbo.fn_varbintohexstr(CONVERT(VARBINARY(1),ASCII(SUBSTRING(@decodedString,num,1)))),3,3))
        FROM dbo.numbers 
        WHERE num BETWEEN 1 AND LEN(@decodedString) AND SUBSTRING(@decodedString,num,1) like '[^a-zA-Z0-9*-.!_]' ESCAPE '!'
    END
    ELSE
    BEGIN
        SELECT @encodedString = @decodedString 
    END
    
    RETURN @encodedString
    
    END
    GO
    

    The script is fully available on SQL Server Central (registration required)

提交回复
热议问题