Null value in a parameter varbinary datatype

半世苍凉 提交于 2019-11-28 03:01:55

问题


How can I add a null value in a parameter varbinary datatype?

When I execute the following code:

using (SqlConnection myDatabaseConnection1 = new SqlConnection(myConnectionString.ConnectionString))
{
    using (SqlCommand mySqlCommand = new SqlCommand("INSERT INTO Employee(EmpName, Image) Values(@EmpName, @Image)", myDatabaseConnection1))
    {
        mySqlCommand.Parameters.AddWithValue("@EmpName", textBoxEmpName.Text);
        mySqlCommand.Parameters.AddWithValue("@Image", DBNull.Value);
        myDatabaseConnection1.Open();
        mySqlCommand.ExecuteNonQuery();
    }
}

I get the following System.Data.SqlClient.SqlException:

Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.


回答1:


You can try something like this:-

cmd.Parameters.Add( "@Image", SqlDbType.VarBinary, -1 );

cmd.Parameters["@Image"].Value = DBNull.Value;



回答2:


I dont know the reason why "DBNull.Value" does not work for me. And I figure out another solution can solve this problem.

cmd.Parameters["@Image"].Value = System.Data.SqlTypes.SqlBinary.Null;



回答3:


try this :

mySqlCommand.Parameters.AddWithValue("@Image", new byte[]{});



回答4:


sqlCommand.Parameters.AddWithValue("@image", SqlBinary.Null);



回答5:


i do it like this without a problem

SqlParameter image= new SqlParameter("@Image", SqlDbType.VarBinary, System.DBNull.Value);
mySqlCommand.Parameters.Add(image);



回答6:


Set null value in your Stored Procedure. Doesn't need to do anything else.

ex. @photo varbinary(max) = null,

ALTER PROCEDURE [dbo].[InsertOurTeam]
    @name nvarchar(50),
    @Sname nvarchar(50),
    @designation nvarchar(50),
    @photo varbinary(max) = null,
    @Pname nvarchar(50)=null,
    @psize bigint=null,
    @id int output
    AS
    BEGIN

        SET NOCOUNT ON;
        insert into OurTeam values (@name,@Sname,@designation,@photo,@Pname,@psize);

        select @id= SCOPE_IDENTITY();
END


来源:https://stackoverflow.com/questions/18170985/null-value-in-a-parameter-varbinary-datatype

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