Convert UTF8 to ANSI


CREATE FUNCTION dbo.Utf8toAnsi
(
        @source VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
    RETURN      CASE
                        -- 2 byte
                        WHEN @source LIKE CONCAT('%[', 0xC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF, '][', 0x808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF, ']%') THEN CAST(CONCAT('<?xml version="1.0" encoding="UTF-8"?><![CDATA[', @source, ']]>') AS XML).value('(text()[1])', 'VARCHAR(MAX)')
                        -- 3 byte
                        WHEN @source LIKE CONCAT('%[', 0xE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEF, '][', 0x808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF, '][', 0x808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF, ']%') THEN CAST(CONCAT('<?xml version="1.0" encoding="UTF-8"?><![CDATA[', @source, ']]>') AS XML).value('(text()[1])', 'VARCHAR(MAX)')
                        -- 4 byte
                        WHEN @source LIKE CONCAT('%[', 0xF0F1F2F3F4F5F6F7, '][', 0x808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF, '][', 0x808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF, '][', 0x808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF, ']%') THEN CAST(CONCAT('<?xml version="1.0" encoding="UTF-8"?><![CDATA[', @source, ']]>') AS XML).value('(text()[1])', 'VARCHAR(MAX)')
                        -- 1 byte
                        ELSE @source
                END;
END;