在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中文網其他相關文章!