Pregunta

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.

¿Fue útil?

Solución 3

You can try something like this:-

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

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

Otros consejos

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;
sqlCommand.Parameters.AddWithValue("@image", SqlBinary.Null);

try this :

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

i do it like this without a problem

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

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top