How convert a Byte[] to a data to insert a value in a varbinary(max) column in SQL Server?

拜拜、爱过 提交于 2020-05-29 08:56:14

问题


I have a object with a byte[] property, and I would like to convert this value to the correct value to can insert it into the database using T-SQL.

But I don't know how I could convert the byte[] to the correct value for T-SQL for the insert.

Thanks.


回答1:


Create a Console Application project and try this code

// Sample Class
public class MyClass
{
    public byte[] data;
}

// Main 
static void Main(string[] args)
{
    MyClass cls = new MyClass();
    using (SqlConnection cn = new SqlConnection("CONNECTION STRING"))
    {
        cn.Open();
        using (SqlCommand cmd = new SqlCommand("insert into MyTable values (@data)", cn))
        {
            cmd.Parameters.AddWithValue("@data", cls.data);
            cmd.ExecuteNonQuery();
        }
    }
}



回答2:


You want to convert to VarBinary.

See the following:

SQL Server Data Type Mappings

simple example (setting command parameter)

byte[] data;
command.Parameters.Add("@data", SqlDbType.VarBinary).Value = data;

T-SQL example of how to pass in varbinary

CREATE PROCEDURE YourStoredProc
    @data varbinary(max)
AS
BEGIN
  -- your code
END


来源:https://stackoverflow.com/questions/43375537/how-convert-a-byte-to-a-data-to-insert-a-value-in-a-varbinarymax-column-in-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!