TSQL - How to URL Encode

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

    How about this one by Peter DeBetta:

    CREATE FUNCTION dbo.UrlEncode(@url NVARCHAR(1024))
    RETURNS NVARCHAR(3072)
    AS
    BEGIN
        DECLARE @count INT, @c NCHAR(1), @i INT, @urlReturn NVARCHAR(3072)
        SET @count = LEN(@url)
        SET @i = 1
        SET @urlReturn = ''    
        WHILE (@i <= @count)
         BEGIN
            SET @c = SUBSTRING(@url, @i, 1)
            IF @c LIKE N'[A-Za-z0-9()''*\-._!~]' COLLATE Latin1_General_BIN ESCAPE N'\' COLLATE Latin1_General_BIN
             BEGIN
                SET @urlReturn = @urlReturn + @c
             END
            ELSE
             BEGIN
                SET @urlReturn = 
                       @urlReturn + '%'
                       + SUBSTRING(sys.fn_varbintohexstr(CAST(@c AS VARBINARY(MAX))),3,2)
                       + ISNULL(NULLIF(SUBSTRING(sys.fn_varbintohexstr(CAST(@c AS VARBINARY(MAX))),5,2), '00'), '')
             END
            SET @i = @i +1
         END
        RETURN @urlReturn
    END
    

提交回复
热议问题