SQL Server 2005のNullable ImageフィールドにDBNULL.VALUEを挿入できないのはなぜですか?
-
13-11-2019 - |
質問
SQL Server 2005のNullabodiceTagCodeフィールドにDBNull.Value
を挿入できないのはなぜですか?
このコードを試してみました:
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();
.
項目はimage
型です。
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
.
Customer
がDBNull.Value
だけ問題を抱えているのはなぜですか?image
を使用しないのはなぜですか?
解決
これを試すことができます:
command.Parameters.Add("@Photo", SqlDbType.Image).Value = DBNull.Value;
. 他のヒント
これは、SqlParameter.sqlsbTypeを明示的に定義していないという事実を考慮して、Nvarcharを想定していると思います。AddWithValueを使用して、新しいSQLParameterを追加し、SQLDBTYPE.Imageを明示的に設定しようとしています。
これは msdn ref デフォルトはnvarcharです。
SQLDBTYPE.Image として、パラメータの型を明示的に指定する必要があります。
これはこのように解決しました:
If (Photo.Equals(DBNull.Value)) Then
cmd.Parameters.Add("Photo", SqlDbType.Image).Value = DBNull.Value
Else
cmd.Parameters.AddWithValue("Photo", Photo)
End If
. 所属していません StackOverflow