Handling unicode characters that aren't displayed correctly in SQL query

后端 未结 3 1552
长情又很酷
长情又很酷 2021-01-21 18:44

Here is the SQL query:

DECLARE @objname nvarchar(255)
set @objname=\'漢字\'
select @objname

When I run this query in Microsoft SQL Server Managem

相关标签:
3条回答
  • 2021-01-21 19:10

    You should use this:

    DECLARE @objname nvarchar(255)
    set @objname = N'漢字'
    select @objname
    
    0 讨论(0)
  • 2021-01-21 19:13

    NVarchar variable are denoted by N'<Value> so it would be

    DECLARE @objname nvarchar(255)
    set @objname=N'漢字'
    select @objname
    

    Now the output will be 漢字 as it has been set. Run above code.

    0 讨论(0)
  • 2021-01-21 19:14

    Adding some context around the other answers:

    You need to declare your string assignment using the N prefix (the N stands for "National Character") as you need to explicitly say you are passing a string containing unicode characters here (or an nchar, ntext etc if you were using those).

    Microsoft's description is

    Prefix a Unicode character string constants with the letter N to signal UCS-2 or UTF-16 input, depending on whether an SC collation is used or not. Without the N prefix, the string is converted to the default code page of the database that may not recognize certain characters. Starting with SQL Server 2019 preview, when a UTF-8 enabled collation is used, the default code page is capable of storing UNICODE UTF-8 character set.

    So your assignment will as per other answers be set @objname = N'漢字'

    You should also be aware to use the prefix in other instances, such as where clauses when filtering on nvarchar columns, otherwise you can encounter issues such as performance degradation from implicit conversions.

    0 讨论(0)
提交回复
热议问题