How to solve “unable to switch the encoding” error when inserting XML into SQL Server

后端 未结 8 2001
醉梦人生
醉梦人生 2020-11-28 07:29

I\'m trying to insert into XML column (SQL SERVER 2008 R2), but the server\'s complaining:

System.Data.SqlClient.SqlException (0x80131904):
XML

8条回答
  •  萌比男神i
    2020-11-28 08:07

    It took me forever to re-solve this problem.

    I was doing an INSERT statement into SQL Server as something like:

    UPDATE Customers 
    SET data = 'Teno';
    

    and this gives the error:

    Msg 9402, Level 16, State 1, Line 2
    XML parsing: line 1, character 39, unable to switch the encoding

    And the really, very simple fix is to:

    UPDATE Customers 
    SET data = N'Teno';
    

    The difference is prefixing the Unicode string with N:

    N'Teno'

    In the former case, an unprefixed string is assumed to be varchar (e.g. Windows-1252 code-page). When it encounters the encoding="utf-16" inside the string, there is a conflict (and rightly so, since the string isn't utf-16).

    The fix is to pass the string to SQL server as an nvarchar (i.e. UTF-16):

    N''

    That way the string is UTF-16, which matches the utf-16 encoding that the XML says it is. The carpet matches the curtains, so to speak.

提交回复
热议问题