6

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!!!

4
  • 2
    So what have you tried so far? Commented Mar 3, 2013 at 15:25
  • 3
    Why don't use want to use a parameter? Commented Mar 3, 2013 at 15:34
  • Which DBMS are you using? Oracle? Postgres? Commented Mar 3, 2013 at 15:41
  • @usr it can be useful. For example, you need to generate INSERT ... from existing data and apply to some other DB Commented Nov 24, 2020 at 20:48

2 Answers 2

9

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 + ")";
Sign up to request clarification or add additional context in comments.

15 Comments

@usr: The OP specifically asked for a solution without using a parameteried query.
Did not see that. What an odd requirement and he's probably mistaken with that. I fixed a typo in your code.
@user1704457: Try with the code as it looks now, with 0h in the code, not 0x. That was an edit made by usr.
"SELECT 0h12345f" does not work. Is it supposed to? "SELECT 0x12345f" does.
This question will teach me not trying to work on such vague and misguided questions. It is unclear to me if the OP even wants this solution. He just said he wants a T-SQL solution if I interpret his rude and vague statement correctly. We are all wasting our time here.
|
0

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....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.