Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing special unicode characters in SQL Server and retrieving in .NET [duplicate]

I cannot properly store special unicode characters in SQL Server and then retrieve them.

SQL Server setup:

create table TestUni
(
    UniCol nvarchar(20)
)

insert into TestUni values ('😅')
insert into TestUni values ('é›»')

Now this command returns question marks:

select len(UniCol), UniCol from TestUni

2    ??
1    ?

When I create a .NET client to read the data, it also returns question marks:

var sqlConnection = new SqlConnection("***");

sqlConnection.Open();

var sqlCommand = new SqlCommand("select * from TestUni", sqlConnection);
        var reader = sqlCommand.ExecuteReader();

var str = string.Empty;

while(reader.Read())
{
    str += reader["UniCol"];
}

File.WriteAllText("d:\\test.txt", str);

The contents of the file:

enter image description here

How to properly retrieve special characters from database?

like image 707
Martin Staufcik Avatar asked Jan 16 '19 13:01

Martin Staufcik


People also ask

How do you handle special characters in SQL query?

Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence. When you use braces to escape a single character, the escaped character becomes a separate token in the query. Use the backslash character to escape a single character or symbol.

How does SQL Server handle Unicode characters?

SQL Server UNICODE() Function The UNICODE() function returns an integer value (the Unicode value), for the first character of the input expression.


1 Answers

You need to use N prefix to indicate a unicode value going in

create table TestUni
(
  UniCol nvarchar(20)
)

insert into TestUni values ('😅')
insert into TestUni values ('é›»')
insert into TestUni values (N'😅')
insert into TestUni values (N'é›»')

select len(UniCol), UniCol from TestUni
like image 68
Jamie Pollard Avatar answered Oct 18 '22 22:10

Jamie Pollard