8

How can I store a string in a varbinary(max) column?

I'm havig trouble in the convertion process i'm doing this:

    cmd.CommandText = "Insert into " + bdcombo.Text + ".dbo.nomes (id, nome) values (@id, @nome)";
    cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlcon;

    cmd.Parameters.Add("@nome", SqlDbType.VarBinary, 20).Value = Convert.ToSByte(textBox1.Text);
7
  • 4
    Why are you using varbinary to store strings? Commented Nov 24, 2011 at 10:30
  • why do you want to store a string in a varbinary column?? Can't you store it in varchar one Commented Nov 24, 2011 at 10:31
  • what problem you're facing any error? exception? Commented Nov 24, 2011 at 10:32
  • @Oded I have a situation where I'm storing text documents of different formats (pdf, docx) in a varbinary(max) column for semantic search. Sometimes my document is just raw text, so this is the way to handle that. Commented Mar 7, 2017 at 14:47
  • @Scott - PDF is not text (nor is docx, which is, technically XML, which yes, technically is a textual format). Commented Mar 7, 2017 at 16:43

1 Answer 1

18

If you want to store a string, use [n]varchar(max).

If you must use varbinary(max), then to get the bytes you must use an encoding, for example:

byte[] theBytes = Encoding.UTF8.GetBytes(theString);

and later:

string theString = Encoding.UTF8.GetString(theBytes);

(when reading)

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

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.