将 US-ASCII 导入 SQL 服务器

Importing US-ASCII into SQL Server

我正在尝试创建一个数据库,作为正在生成的一系列 XML 文件的存储库。

在我的 SQL 服务器数据库中,我有一个类似于下面的 table 来存储 XML 文件:

CREATE TABLE [dbo].[MyTable] 
(
    [InternalID] INT NOT NULL IDENTITY, 
    [ExternalID] INT NOT NULL,
    [XmlData] XML NOT NULL
)

每个 XML 文件都在 US-ASCII 中使用以下 header 编码:

<?xml version="1.0" encoding="us-ascii"?>

我已经创建了一个存储过程来将文件插入 table,我正在使用 .NET 使用以下命令访问它:

int externalKey = someint;
string myXML = File.ReadAllText(xmlFilePath);

using (SqlCommand myCommand = new SqlCommand ("My_Stored_Proc", myConnection)) {
    myCommand.CommandType = SqlCommandType.StoredProcedure;
    myCommand.Parameters.Add(new SqlParameter ("@ExternalID", externalID));
    myCommand.Parameters.Add(new SqlParameter ("@XmlData", myXML));
    myCommand.ExecuteNonQuery();
}

当我的代码尝试 运行 时,它在尝试执行 non-query 时遇到以下 SqlException

XML parsing: line 1, character 41, unable to switch the encoding

如果我在执行之前通过将 encoding="us-ascii" 替换为使用 UTF-8 的字符串来修改字符串,则一切正常。但是最好不要在数据库中修改源。

这是不可能的。见文章"Limitations of the xml Data Type":https://technet.microsoft.com/en-us/library/ms187107%28v=sql.90%29.aspx?f=255&MSPPError=-2147217396

XML provides its own encoding. Collations apply to string types only. The xml data type is not a string type. However, it does have string representation and allows casting to and from string data types.

和(强调我的):

If you copy and paste XML as a string literal into the Query Editor window in SQL Server Management Studio, you might experience [N]VARCHAR string encoding incompatibilities. This will depend on the encoding of your XML instance. In many cases, you may want to remove the XML declaration.

读入你的 XML 文件时,只需删除 <?xml ?> 序曲并直接插入。鉴于 ASCII 是 UTF-8 的子集,您不会 运行 遇到任何问题。