首頁 >資料庫 >mysql教程 >如何在 SQL Server 中將 UTF-8 文字轉換為 ISO 8859-1?

如何在 SQL Server 中將 UTF-8 文字轉換為 ISO 8859-1?

Linda Hamilton
Linda Hamilton原創
2025-01-03 13:37:39940瀏覽

How to Convert UTF-8 Text to ISO 8859-1 in SQL Server?

在SQL Server 轉換文字值從UTF-8 轉換為ISO 8859-1

問題:

問題:問題:

CREATE FUNCTION dbo.DecodeUTF8String (@value varchar(max))
RETURNS nvarchar(max)
AS
BEGIN
    -- Check if the string is ASCII or null, as no conversion is needed.
    IF (@value IS NULL
        OR @value NOT LIKE '%[^ -~]%' COLLATE Latin1_General_BIN
    )
        RETURN @value;

    DECLARE @result nvarchar(max);

    -- Split the UTF-8 string into octets and calculate their codepoints.
    WITH octets AS
    (
        SELECT position, highorderones, partialcodepoint
        FROM numbers a
        CROSS APPLY (SELECT octet = ASCII(SUBSTRING(@value, position, 1))) b
        CROSS APPLY (SELECT highorderones = 8 - FLOOR(LOG( ~CONVERT(tinyint, octet) * 2 + 1)/LOG(2))) c
        CROSS APPLY (SELECT databits = 7 - highorderones) d
        CROSS APPLY (SELECT partialcodepoint = octet % POWER(2, databits)) e
    ),
    codepoints AS
    (
        SELECT position, codepoint
        FROM
        (
            SELECT position, highorderones, partialcodepoint
            FROM octets
            WHERE highorderones <> 1
        ) lead
        CROSS APPLY (SELECT sequencelength = CASE WHEN highorderones in (1,2,3,4) THEN highorderones ELSE 1 END) b
        CROSS APPLY (SELECT endposition = position + sequencelength - 1) c
        CROSS APPLY
        (
            SELECT codepoint = SUM(POWER(2, shiftleft) * partialcodepoint)
            FROM octets
            CROSS APPLY (SELECT shiftleft = 6 * (endposition - position)) b
            WHERE position BETWEEN lead.position AND endposition
        ) d
    )
    -- Concatenate the codepoints into a Unicode string.
    SELECT @result = CONVERT(xml,
        (
            SELECT NCHAR(codepoint)
            FROM codepoints
            ORDER BY position
            FOR XML PATH('')
        )).value('.', 'nvarchar(max)');

    RETURN @result;
END
GO

問題:問題:> Server 中的列採用UTF-8 編碼,您需要將文字轉換並儲存為ISO 8859-1

SELECT *, NewColumn1 = dbo.DecodeUTF8String(Column1)
FROM Table1
WHERE Column1 <> dbo.DecodeUTF8String(Column1)

解決方案:

要實現此轉換,您可以使用自訂函數。以下程式碼提供了一個實作:用法: 若要將轉換套用到名為「Column1」的資料列,您可以使用下列查詢:此查詢將建立一個新欄位“NewColumn1”,其中包含轉換為ISO 8859-1 的UTF-8 文字編碼。

以上是如何在 SQL Server 中將 UTF-8 文字轉換為 ISO 8859-1?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn