问题
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