Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Byte Array to string using TransactSQL

We are store string values in a database using varBinary type using c# and BinaryFormatter.We convert to byte array and then we save to DataBase

public static byte[] ToBytes(stringvalue)
{
  if (value == null)
    return null;

  byte[] inMemoryBytes;
  using (MemoryStream inMemoryData = new MemoryStream())
  {
    new BinaryFormatter().Serialize(inMemoryData, value);
    inMemoryBytes = inMemoryData.ToArray();
  }

  return inMemoryBytes;
}

OK, So if we save char "a", we can see "0x0001000000FFFFFFFF0100000000000000060100000001610B" in the database.After we can retrieve the data and convert again to string.
Can we convert this binary value ("0x0001000000FFFFFFFF0100000000000000060100000001610B") to char ("a") only using transact SQL (so we can do modifications, inserts, comparations from sql server console)?

Thanks a lot.

like image 505
Oscar Avatar asked Jan 25 '10 13:01

Oscar


People also ask

How do I convert a byte array to a string?

You can choose from several encoding options to convert a byte array into a string: Encoding.ASCII: Gets an encoding for the ASCII (7-bit) character set. Encoding.BigEndianUnicode: Gets an encoding for the UTF-16 format using the big-endian byte order. Encoding.Default: Gets an encoding for the system's current ANSI code page.

How to decode a byte array to string in Java?

Though, we should use charset for decoding a byte array. There are two ways to convert byte array to String: By using String class constructor; By using UTF-8 encoding; By using String Class Constructor. The simplest way to convert a byte array into String, we can use String class constructor with byte[] as the constructor argument.

What is the difference between a byte array and string?

Since bytes is the binary data while String is character data. It is important to know the original encoding of the text from which the byte array has created. When we use a different character encoding, we do not get the original string back. Suppose, we have to read byte array from a file which is encoded in " ISO_8859_1 ".

How to convert binary data type to Base64 string in MySQL?

We convert the data in the table into JSON using the built-in hint " FOR JSON AUTO ". This operating will automatically convert any binary data type in the table into BASE64 String. Next, Using the function OPENJSON, we extract the BASE64 String from the JSON


1 Answers

You could to use something simpler, as

Encoding.Default.GetBytes("a");

That will return "61" and can be more easily translated to a varchar, just running this:

create table #sample (content varbinary(max));
insert into  #sample values (0x61)
select cast(content as varchar) from #sample
like image 110
Rubens Farias Avatar answered Sep 19 '22 11:09

Rubens Farias