如何将字符串转换为以UTF-8编码的字符串,反之亦然?

时间:2010-08-27 14:29:25

标签: sql-server sql-server-2008

A使用UTF-8解码的字符串%c3%adí,但使用ASCII解码为Ã

我需要使用UTF-8编码对其进行解码,我该怎么做?

这是一个值的选择以及应该是什么......

SELECT
('%c3%81') as 'Á (81 = 129)',
('%c3%89') as 'É (89 = 137)',
('%c3%8d') as 'Í (8d = 141)',
('%c3%93') as 'Ó (93 = 147)',
('%c3%9a') as 'Ú (9a = 154)'


SELECT
('%c3%a1') as 'á (a1 = 161)',
('%c3%a9') as 'é (a9 = 169)',
('%c3%ad') as 'í (ad = 173)',
('%c3%b3') as 'ó (b3 = 179)',
('%c3%ba') as 'ú (ba = 186)'

1 个答案:

答案 0 :(得分:1)

这个功能似乎可以胜任。

CREATE FUNCTION [dbo].[UrlDecodeUTF8](@URL varchar(3072))
RETURNS varchar(3072)
AS
BEGIN 
    DECLARE @Position INT,
        @Base CHAR(16),
        @Code INT,
        @Pattern CHAR(21)

    SELECT @URL = REPLACE(@URL, '%c3', '')

    SELECT  @Base = '0123456789abcdef',
        @Pattern = '%[%][0-9a-f][0-9a-f]%',
        @Position = PATINDEX(@Pattern, @URL)

    WHILE @Position > 0
        SELECT @Code = Cast(CONVERT(varbinary(4), '0x' + SUBSTRING(@URL, @Position + 1, 2), 1) As int),
            @URL = STUFF(@URL, @Position, 3, NCHAR(@Code + 64)),
            @Position = PATINDEX(@Pattern, @URL)

    RETURN REPLACE(@URL, '+', ' ')

END