Peter Larsson Blog

Patron Saint of Lost Yaks

Convert UTF-8 string to ANSI

CREATE FUNCTION dbo.fnConvertUtf8Ansi
(
    @Source VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
    DECLARE @Value SMALLINT = 160,
            @Utf8 CHAR(2),
            @Ansi CHAR(1)

    IF @Source NOT LIKE '%[ÂÃ]%'
        RETURN  @Source

    WHILE @Value <= 255
        BEGIN
            SELECT  @Utf8 = CASE
                                WHEN @Value BETWEEN 160 AND 191 THEN CHAR(194) + CHAR(@Value)
                                WHEN @Value BETWEEN 192 AND 255 THEN CHAR(195) + CHAR(@Value - 64)
                                ELSE NULL
                            END,
                    @Ansi = CHAR(@Value)

            WHILE CHARINDEX(@Source, @Utf8) > 0
                SET    @Source = REPLACE(@Source, @Utf8, @Ansi)

            SET    @Value += 1
        END

    RETURN  @Source
END

Legacy Comments


Arnold Fribble
2011-09-15
re: Convert UTF-8 string to ANSI
From long, long ago:
www.sqlteam.com/forums/topic.asp?TOPIC_ID=62406

Shawn M.
2012-02-04
re: Convert UTF-8 string to ANSI
What would be the advantage of having the ANSI code versus having the UTF-8 code? I, for one, am fond of UTF-8 and typically use that style of code when I work on the Indianapolis Jiu Jitsu website that I help out with. The site runs fluently and has yet to have any issues. Does converting the code to ANSI offer any benefits in terms of speed or ease of use?