【问题标题】:how to pass null value as a datetime to sql server (DAL Layer)如何将空值作为日期时间传递给 sql server(DAL 层)
【发布时间】:2015-03-20 21:10:06
【问题描述】:

我在 sql server 中有一个列(可为空,但它是日期时间)..

如果没有选择用户任何日期,我需要为此字段传递空值,我在下面做了这样的操作

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        DateTime expiryDate;
        DateTime? expDate = null;
         if (chkExpDate.Checked == true)
        {
            expiryDate = Convert.ToDateTime(txtExpiryDate.Text);
        }
        else if (expDate.HasValue)
        {
            expiryDate = expDate.Value;
        }
        else
            expiryDate = Convert.ToDateTime(DBNull.Value);
         // here I am getting error like "object cannot be cast from DBNULL or value

如果我必须克服这个问题我需要做什么..如果用户没有被选择任何日期我需要传递空值我该怎么做..

有人可以帮忙解决这个问题吗。非常感谢

DAL

public bool ReAssignLicense(string certificateID, string serialNumber, string newEmail, string ticketID, string backupBy, string customerName, DateTime expDate)
    {
        List<SqlParameter> ParaList = new List<SqlParameter>();
        ParaList.Add(new SqlParameter("@certificate", certificateID));
        ParaList.Add(new SqlParameter("@certSN", serialNumber));
        ParaList.Add(new SqlParameter("@newemail", newEmail));
        ParaList.Add(new SqlParameter("@ticket", ticketID));
        ParaList.Add(new SqlParameter("@bkpBy", backupBy));
        ParaList.Add(new SqlParameter("@customer_name", customerName));
        ParaList.Add(new SqlParameter("@exp_date", expDate));

        return SqlHelper.ExecuteNonQuery(new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString),CommandType.StoredProcedure,"sp_Update",ParaList.ToArray()) > 0;
    }

【问题讨论】:

  • 不要忘记投票并标记为已接受......因为它对你有用。

标签: c# sql-server datetime null nullable


【解决方案1】:

你可以这样做

SqlParameter moFrom1Param = new SqlParameter("@MoFrom1", expairydate == null 
           ? DBNull.Value : expairydate);
            moFrom1Param.IsNullable = true;
            moFrom1Param.Direction = ParameterDirection.Input;
            moFrom1Param.SqlDbType = SqlDbType.DateTime;
            cmd.Parameters.Add(moFrom1Param);

您可以将 DatTime 变量设置为可空变量,无需执行任何操作即可处理您的问题。

由于您的 expiryDate 可以为空,您可以直接在 sql 命令中传递 thsi 字段,或者从数据库层调用您正在调用的查询。

你可以像这样改变这一行

expiryDate = DateTime.MinValue;

查看此帖子:http://www.dotnetperls.com/datetime-minvalue

//
    // This won't compile!
    //
    // DateTime dateTime1 = null;
    //
    // This is the best way to null out the DateTime.
    //
    DateTime dateTime2 = DateTime.MinValue;

【讨论】:

  • sql server 中的 dateTime 字段为 null 所以。我也可以插入 null .. 但抱歉我不能插入最小值
  • 因为你有可以为空的字段,你可以直接在sql参数中传递expiryDate...
  • 我也不能通过mindate,因为它是到期日......我不能输入任何日期,因为我只需要传递null或用户选择的日期......我该怎么做...... ...
  • 如果您的 expDate 为空,请不要传递参数,因为您在 sql 中的日期时间字段为空
  • 你的意思是如果没有选择用户,则不需要从前端传递日期...所以我们可以在 DAL 中进行修改...(即在 DAL 层中设置空值)
【解决方案2】:

检查一下

protected void btnSubmit_Click(object sender, EventArgs e)
{
  DateTime? expDate = null;
  if (chkExpDate.Checked == true)
  {
    expDate = Convert.ToDateTime(txtExpiryDate.Text);
  }

我在这里将您的 DateTime 变量设置为可为空。

public bool ReAssignLicense(string certificateID, string serialNumber, string newEmail, string ticketID, string backupBy, string customerName, DateTime? expDate)
{
  List<SqlParameter> ParaList = new List<SqlParameter>();
  ParaList.Add(new SqlParameter("@certificate", certificateID));
  ParaList.Add(new SqlParameter("@certSN", serialNumber));
  ParaList.Add(new SqlParameter("@newemail", newEmail));
  ParaList.Add(new SqlParameter("@ticket", ticketID));
  ParaList.Add(new SqlParameter("@bkpBy", backupBy));
  ParaList.Add(new SqlParameter("@customer_name", customerName));

  if (expDate != null)
    ParaList.Add(new SqlParameter("@exp_date", expDate));

  return SqlHelper.ExecuteNonQuery(new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString), CommandType.StoredProcedure, "sp_Update", ParaList.ToArray()) > 0;
}

【讨论】:

    【解决方案3】:

    您好,如果我正确理解了您的问题,那么您应该在最后一个条件下将 expiryDate 设置为 null。

    同样,您将需要更改变量声明 DateTime expiryDate 作为可空类型与您对 DateTime 所做的相同吗? expDate = null;

    所以上面发布的修改后的语法如下

            DateTime? expiryDate;
            DateTime? expDate = null;
            if (chkExpDate.Checked == true)
            {
                expiryDate = Convert.ToDateTime(txtExpiryDate.Text);
            }
            else if (expDate.HasValue)
            {
                expiryDate = expDate.Value;
            }
            else
    
                expiryDate = null;
    

    希望这对你有用。

    【讨论】:

      【解决方案4】:

      SQL Server 中,只需在日期时间列中插入NULL

      INSERT INTO Table(name, datetimeColumn, ...)
      VALUES('foo bar', NULL, ..);
      

      或者,您可以使用DEFAULT 约束:

      ...
      DateTimeColumn DateTime DEFAULT NULL,
      ...
      

      然后你可以在INSERT statemnt 中完全忽略它,它会被插入到NULL 值中:

      INSERT INTO Table(name, ...)
      VALUES('foo bar', ..);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 2015-10-20
        • 1970-01-01
        • 2019-05-30
        相关资源
        最近更新 更多