Over het algemeen heeft SQL Server UTF-8 niet hoog in het vaandel. .NET heeft echter methoden om dit te doen en u kunt ze bereiken via CLR-integratie.
Compileer dit met C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
namespace UtfLib
{
public static class UtfMethods
{
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static SqlBinary NVarCharToUtf8(SqlString inputText)
{
if (inputText.IsNull)
return new SqlBinary(); // (null)
return new SqlBinary(Encoding.UTF8.GetBytes(inputText.Value));
}
[SqlFunction(IsDeterministic = true, IsPrecise = true)]
public static SqlString Utf8ToNVarChar(SqlBinary inputBytes)
{
if (inputBytes.IsNull)
return new SqlString(); // (null)
return new SqlString(Encoding.UTF8.GetString(inputBytes.Value));
}
}
}
Importeer de assembly in uw database en creëer de externe functies:
CREATE ASSEMBLY UtfLib
FROM 'C:\UtfLib.dll'
GO
CREATE FUNCTION NVarCharToUtf8 (@InputText NVARCHAR(MAX))
RETURNS VARBINARY(MAX)
AS EXTERNAL NAME UtfLib.[UtfLib.UtfMethods].NVarCharToUtf8
GO
CREATE FUNCTION Utf8ToNVarChar (@InputBytes VARBINARY(MAX))
RETURNS NVARCHAR(MAX)
AS EXTERNAL NAME UtfLib.[UtfLib.UtfMethods].Utf8ToNVarChar
Laatste stap, je moet clr
. inschakelensp_configure 'clr enabled',1
GO
RECONFIGURE
GO
sp_configure 'clr enabled' -- make sure it took
GO
en voilà!
SELECT dbo.Utf8ToNVarChar(DATA) FROM [dbo].[TABLE_NAME]