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?
Asked
Active
Viewed 2,900 times
1
-
5You mean like `Encoding.UTF8Encoding.ToByteArray(string)`? – Jeremy Holovacs Apr 10 '13 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 – MethodMan Apr 10 '13 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? – Brian Apr 10 '13 at 20:59
1 Answers
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();
}
}