处理 SQLParameter 中可能为空的日期时间值

Dealing with potentially null datetime value in a SQLParameter

我正在尝试做我认为非常简单的事情,但遇到了问题。我在 .NET 应用程序中有使用 SQLCommand 将新记录插入 table 的代码。

我传递的可能是日期时间值,也可能是空值。下面的代码似乎不起作用:

command.Parameters.AddWithValue("@SettleDate", 
IIf(String.IsNullOrEmpty(SettleDate), Nothing, DateTime.Parse(SettleDate)))

其中 "SettleDate" 是一个包含日期的字符串,该日期可以为空。我认为此代码将涵盖不尝试解析空值的情况,但是当它是 运行 时,我收到以下错误,该错误看起来来自 Datetime.Parse 方法:

String reference not set to an instance of a String.
Parameter name: s

怎么会这样?如果 "SettleDate" 为空,则它永远不会到达解析方法。

您应该将VB.NET的短路运算符与DbNull.Value

一起使用
If(String.IsNullOrEmpty(SettleDate), DBNull.Value, DateTime.Parse(SettleDate)))

The IF operator, contrary to IIF function doesn't try to evaluate both sides of the expression if the first one is true. Note also that to pass a null value to an SqlParameter you use DbNull.Value.