1

I have to do a query to insert a value in a SQL table. The type of the value is varbinary and I have a string to insert with an hex value in it. So I tried to use the SQL Convert Function like this:

using (SqlCommand dbCommand = new SqlCommand("INSERT INTO [Link] ([Record]) values (CONVERT(varbinary,@myrecord);", dbConn))

dbCommand.Parameters.Add("myrecord", System.Data.SqlDbType.VarBinary).Value = recordString;

but I have this Error: Failed to convert parameter value from a String to a Byte[].

So I tried to convert my string to byte[], but all the function I found also on this site convert my string to byte changing its value, so it's not good because my string has inside the value I need to insert in the table.

Recap: I have a string with this value: "0x54000000006C00000000099W043100300030003100" how can I add it in a SQL table with a varbinary field?

3
  • If you are using the CONVERT function in your sqlcommand, why are you trying to add a VarBinary parameter? In mean, doesn't this work?: dbCommand.Parameters.Add("myrecord", System.Data.SqlDbType.VarChar).Value = recordString; Commented Jan 12, 2016 at 16:24
  • when I tried this the value of my string is converted and not what I wanted. Commented Jan 12, 2016 at 16:36
  • 1
    Example is not a valid hex string, there is a "W" in the middle. Commented Jan 12, 2016 at 16:59

2 Answers 2

2

Ok, i think i understand now. If you are using sql server 2008+, you can do this:

using (SqlCommand dbCommand = new SqlCommand("INSERT INTO [Link] ([Record]) values (CONVERT(varbinary,@myrecord,1);", dbConn))

dbCommand.Parameters.Add("myrecord", System.Data.SqlDbType.VarChar).Value = recordString;

Notice the 1 in CONVERT(varbinary,@myrecord,1). Btw, the example number you gave us is not a valid Hex number...

More info: Msdn

Sign up to request clarification or add additional context in comments.

Comments

0

you can and should be able to do this make sure you adjust the VarBinary Size to fit your case

using(SqlCommand dbCommand = new SqlCommand("INSERT INTO [Link] ([Record]) values(@myrecord);", dbCon))
{
    // Replace 8000, below, with the correct size of the field
    dbCommand.Parameters.Add("@myrecord", System.Data.SqlDbType.VarChar, recordString.Length).Value = recordString;
    dbCommand.ExecuteNonQuery();//wrap around a try catch if you need to catch exceptions
}

3 Comments

I change 8000 with 448 (myvarbinary size) and I have the same error again: Failed to convert parameter value from a String to a Byte[]
@Heisenberg you may need to change your datatype to System.Data.SqlDbType.VarChar
@Heisenberg did that fix the issue

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.