我有一个搜索页面,其中有日期文本字段。用户可以填充此字段,也可以不填充。但是该字段是一个sql存储过程的参数,它被调用来执行搜索查询。
当我遍历代码(日期字段为空)时,我得到一个错误,该值无法转换为datetime
由于查询需要参数,如何将空值转换为datetime?

cmdSearch.Parameters.Add(new SqlParameter("@StartDate", SqlDbType.DateTime));
cmdSearch.Parameters["@StartDate"].Value = Convert.ToDateTime(txtStartDate.Text.Trim());

最佳答案

如果将sql proc中的参数设置为可选参数,则通过提供默认值

CREATE PROCEDURE MyProc
...
@StartDate datetime = null,
....

你可以忽略从C代码中发送参数
DateTime result;
if (DateTime.TryParse(txtStartDate.Text, out result))
{
   cmdSearch.Parameters.Add(new SqlParameter("@StartDate", SqlDbType.DateTime));
   cmdSearch.Parameters["@StartDate"].Value = result;
}

如果文本字段的分析失败,则参数不会添加到参数列表中,数据库将使用默认值。
另外,使用datetime.tryparse(..)可以防止处理异常。

10-02 01:20
查看更多