将DBNUll.value插入到int字段的数据库中?

时间:2014-06-19 11:30:20

标签: sql-server sql-server-2008

当OrderMealdealItemID在以下查询的数据库中为空时,我无法在我的数据库中为OrderMealDealItemID插入null。

  string insertStatementDressing = null;
  insertStatementDressing = @"Insert into OrderDressing(SrNo,DressingID,OrderItemID,OrderID,ProductID,OrderMealDealItemID,IsDeleted,IsApplied,Amount,IsPriceApplied) 
             values('" + odiDress.SrNo + "'," + odiDress.DressingID + "," + odiDress.OrderItemID + "," +
              latestOrderID_onLocal + "," + odiD.ProductID + "," +
              odiDress.OrderMealDealItemID??DBNull.Value
                                      + "," + odiDress.IsDeleted + "," + odiDress.IsApplied + "," + odiDress.Amount + "," + odiDress.IsPriceApplied + ")";

                        db_local.ExecuteStoreCommand(insertStatementDressing);

当我执行此查询时,它会转换为follwing但不是数据库可以接受的完整可执行字符串。

     Insert into OrderDressing(SrNo,
                               DressingID,
                               OrderItemID,
                               OrderID,
                               ProductID,
                               OrderMealDealItemID,
                               IsDeleted,
                               IsApplied,
                               Amount,
                               IsPriceApplied) 
                    values('02785d81-dc9f-4bf1-8050-7498bcb427c7',38,1,20,3,

1 个答案:

答案 0 :(得分:1)

因为您手动创建SQL字符串,所以还需要手动创建NULL值。试试这个:

insertStatementDressing = @"Insert into OrderDressing(SrNo,DressingID,OrderItemID,OrderID,ProductID,OrderMealDealItemID,IsDeleted,IsApplied,Amount,IsPriceApplied) 
values('" + odiDress.SrNo + "'," + odiDress.DressingID + "," + odiDress.OrderItemID + "," +
                                              latestOrderID_onLocal + "," + odiD.ProductID + "," +
                                              odiDress.OrderMealDealItemID.HasValue ? odiDress.OrderMealDealItemID.Value.ToString() : "NULL" + "," + odiDress.IsDeleted + "," + odiDress.IsApplied + "," + odiDress.Amount + "," + odiDress.IsPriceApplied + ")";

请注意,您应该避免编写这样的查询,因为它们容易受到SQL注入(以及其他问题)