Sql server 2005 为什么可以';在SQLServer2005中,是否将DBNull.Value插入到可为空的映像字段中?
为什么我不能将Sql server 2005 为什么可以';在SQLServer2005中,是否将DBNull.Value插入到可为空的映像字段中?,sql-server-2005,c#-2.0,nullable,dbnull,Sql Server 2005,C# 2.0,Nullable,Dbnull,为什么我不能将DBNull.Value插入sql server 2005中可为空的图像-字段 我尝试了以下代码: SqlConnection conn = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=PrescriptionTrackingSystem;Integrated Security=True"); conn.Open(); SqlTransaction tr
DBNull.Value
插入sql server 2005中可为空的图像
-字段
我尝试了以下代码:
SqlConnection conn = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=PrescriptionTrackingSystem;Integrated Security=True");
conn.Open();
SqlTransaction transaction = conn.BeginTransaction();
SqlCommand command = new SqlCommand(@"INSERT INTO Customer(
ID
,Name
,TelephoneNumber
,DateOfBirth,
InsuranceProvider,
PolicyNumber,Photo)
VALUES(
@ID
,@Name
,@TelephoneNumber
,@DateOfBirth,
@InsuranceProvider,
@PolicyNumber,
@Photo)", conn);
command.Transaction = transaction;
command.Parameters.AddWithValue("@ID", 1000);
command.Parameters.AddWithValue("@Name", item.Name);
command.Parameters.AddWithValue("@TelephoneNumber", item.TelephoneNumber);
if (item.DateOfBirth != null)
{
command.Parameters.AddWithValue("@DateOfBirth", item.DateOfBirth);
}
else
{
command.Parameters.AddWithValue("@DateOfBirth", DBNull.Value);
}
command.Parameters.AddWithValue("@InsuranceProvider", item.InsuranceProvider);
command.Parameters.AddWithValue("@PolicyNumber", item.PolicyNumber);
if (item.Photo != null)
{
command.Parameters.AddWithValue("@Photo", item.Photo);
}
else
{
command.Parameters.AddWithValue("@Photo", DBNull.Value);
}
int count = command.ExecuteNonQuery();
transaction.Commit();
conn.Close();
项目类型为客户
public class Customer
{
public string Name { get; set; }
public DateTime? DateOfBirth { get; set; }
public string TelephoneNumber { get; set; }
public string InsuranceProvider { get; set; }
public int? PolicyNumber { get; set; }
public byte [] Photo { get; set; }
}
插入时,我会收到此异常:
Operand type clash: nvarchar is incompatible with image
为什么
DBNull.Value
仅与image
有关?为什么不使用datetime
?我认为这可能是因为您没有明确定义SqlParameter.SqlDbType,并且认为它将假定为NVARCHAR。尝试添加新的SqlParameter并将SqlDbType显式设置为SqlDbType.Image,而不是使用AddWithValue
以下是默认值为NVARCHAR的说明。您需要显式地将参数的类型指定为SqlDbType.Image您可以尝试以下操作:
command.Parameters.Add("@Photo", SqlDbType.Image).Value = DBNull.Value;
我是这样解决的:
If (Photo.Equals(DBNull.Value)) Then
cmd.Parameters.Add("Photo", SqlDbType.Image).Value = DBNull.Value
Else
cmd.Parameters.AddWithValue("Photo", Photo)
End If
存储过程是什么,数据类型是什么?是的。但是我已经发布了我的代码,你可以看到DateTime工作正常。一个空的NVARCHAR可以被转换成DateTime而没有问题。但是,如果出现转换错误,则无法将空NVARCHAR转换为图像。尝试一下,将该参数的SqlDbType设置为Image.Yes。但我已经发布了我的代码,您可以看到DateTime工作正常。是的,这是因为nvarchar与DateTime之间存在隐式转换,并且它会按应有的方式处理空值。即使值为null,也没有从nvarchar到Image的任何隐式转换。转换是否与SqlServer2005或SqlCommand对象关联?