1

I am using SqlConnection and SqlCommand in C# to insert rows of strings (via Parameters.AddWithValue) into SQL Server. One of the columns I need to insert into is a Varbinary. Is there any way to do the conversion in either C# or SQL Server?

3
  • 5
    You mean like Encoding.UTF8Encoding.ToByteArray(string)? Commented Apr 10, 2013 at 20:57
  • Can you post your code as well as an example of what and where in the code you want this conversion to take place Commented Apr 10, 2013 at 20:57
  • Couldn't you cast the string to a varbinary in your SQL? Or do you want it stored in the DB as the original string? Commented Apr 10, 2013 at 20:59

1 Answer 1

2

According to this answer, you can use the CONVERT function to insert a string into a VARBINARY column. Make sure you use the proper encoding, as discussed in that answer.

insert Table_2 (Test) values( CONVERT(varbinary(30), N'this is a test') ) 
select * from Table_2
select CONVERT(nvarchar(30), test) from Table_2

So the C# code would look something like

    // Get from config
    string connectionString = "";

    using (var conn = new SqlConnection(connectionString))
    {
        string sql = "insert Table_2 (Test) values( CONVERT(varbinary(30), @nvarcharParam) )";
        using (var cmd = new SqlCommand(sql, conn))
        {
            var param = cmd.Parameters.AddWithValue("nvarcharParam", "This is a test");
            param.DbType = DbType.String;

            cmd.ExecuteNonQuery();
        }
    }
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.