user1704457
user1704457

Reputation: 79

INSERT BYTE[] TO Sql Without parameter

I want to make a raw SQL query that adds an encrypted value (byte[]) to an SQL column (varbinary) without using parameter like this:

 byte[] value = GetEncryptedValue();
 string query = "INSERT INTO Table1 VALUES('" + value.ToString() + "')";

the column datatype that I want insert into is varbinary. I need some function that uses value.ToString() instead. How to write this ? i just need function like master.dbo.fn_varbintohexstr in sql!!!

Upvotes: 6

Views: 4115

Answers (2)

T.S.
T.S.

Reputation: 19340

Another way to do it, is by using BitConverter

byte[] value = GetEncryptedValue();
string query = 
    "INSERT INTO Table1 (c1) VALUES(0x" + BitConverter.ToString(value).Replace("-", "") + ")";

BitConverter.ToString returns something like 01-02-03....

Upvotes: 0

Guffa
Guffa

Reputation: 700322

A binary literal takes the form 0x6ABCDEF, i.e. 0x followed by bytes in hexadecimal form.

You can use this to turn the byte array into a literal value:

string literal = "0x" + String.Join("", value.Select(n => n.ToString("X2")));

There are not apostrophes around the binary literal:

string query = "INSERT INTO Table1 VALUES(" + literal + ")";

Upvotes: 10

Related Questions