Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode nvarchar to text (SQL Server 2008 R2)?

I have a SQL Server 2008 R2 table with nvarchar(4000) field.

Data that stores this table look like

'696D616765206D61726B65643A5472'

or

'303131' ("011").

I see that each char is encoding to hex.

How can I read those data from table? I don't want write decoding function, I mean that simpler way exists.

P.S. Sorry for my English.

like image 796
xieergai Avatar asked Jun 07 '11 09:06

xieergai


People also ask

Can Nvarchar be converted to VARCHAR?

Use Virtual View to load the data to Data Vault, and in Virtual View, use the CONVERT() function of SQL Server to extract NVARCHAR(MAX) data as VARCHAR.

What encoding is Nvarchar?

For NCHAR / NVARCHAR , the character encoding is UCS-2 or UTF-16, depending if the database collation is using the SC option. The length N in N[VAR]CHAR(N) defines a number of byte-pairs, not bytes. For UCS-2 this corresponds to a number of characters.

Does Nvarchar support Unicode?

Unicode Data Types. Data types nchar, nvarchar, and long nvarchar are used to store Unicode data. They behave similarly to char, varchar, and long varchar character types respectively, except that each character in a Unicode type typically uses 16 bits.

Is Nvarchar a string?

The NVARCHAR data type stores strings of varying lengths. The string can include digits, symbols, and both single-byte and (in some locales) multibyte characters. The main difference between VARCHAR and NVARCHAR data types is the collation order.


1 Answers

SQL Server 2008 actually has a built-in hex-encoding and decoding feature!

Sample (note the third parameter with value "1" when converting your string to VarBinary):

DECLARE @ProblemString VarChar(4000) = '54657374'
SELECT Convert(VarChar, Convert(VarBinary, '0x' + @ProblemString, 1))

Ref: http://blogs.msdn.com/b/sqltips/archive/2008/07/02/converting-from-hex-string-to-varbinary-and-vice-versa.aspx

The advantage of this approach is that you don't need the "Exec" call, which you generally try to avoid, for fear of injection among other things. The disadvantage is that it only works in SQL Server 2008 and later.

like image 170
Tao Avatar answered Sep 20 '22 11:09

Tao