【问题标题】:Return NULL datetime value from T-SQL into C# DataTable ==> DataRow instead of empty string从 T-SQL 返回 NULL 日期时间值到 C# DataTable ==> DataRow 而不是空字符串
【发布时间】:2012-10-21 17:25:22
【问题描述】:

此值 (row[10]) 来自 DataRow 对象,来自 T-SQL 中的 SQL 结果集。我相信它有一个类型“对象”。在我的数据库中,这个特定记录的字段的值为 NULL,但它在我的结果集中返回一个空字符串,而不是空值。我想解决根本问题并让我的结果集返回 NULL 而不是空字符串,但如果这不可能,那么让这段代码更高效就可以了——意思是第一个 sn-p,因为它适用于所有 3 例。

这在 row[10].ToString() 等于空字符串、null 或 DateTime 格式时有效,但我想缩短它。这是我目前的解决方法。

        string temp0 = row[10].ToString();
        DateTime? temp = null;
        if (temp0 == "")
        {
            temp0 = null;
        }
        if (temp0 != null)
        {
            temp = DateTime.Parse(temp0);
        }

        d.date_migrate_prod = temp == null ? null : temp;

这适用于空日期时间值,即实际的日期时间值,但不适用于 row[10] 等于空字符串。

        DateTime? temp = DateTime.Parse(row[10].ToString());
        d.date_migrate_prod = temp == null ? null : temp;

【问题讨论】:

  • 我想您知道DBNull 表示字段中的空值,而null 用于c# 中未分配任何值的引用类型变量。 row[10] 是否引用 varchar 类型的字段?
  • @shahkalpesh。不..这是一个日期时间

标签: c# .net tsql datetime string


【解决方案1】:

正确的做法是:

 DateTime? temp = null; //this is fine
 var indexOfYourColumn = reader.GetOrdinal("columnName");//not necessary but makes iterating faster
 while (reader.Read())
 {
       temp = reader[indexOfYourColumn] != DBNull.Value ? (DateTime?) null : DateTime.Parse(reader[indexOfYourColumn].ToString())
 }

为什么?您不能对空值执行 .ToString() 。然后你需要投喜欢。所以可以为空的 DateTime 到可以为空的 DateTime。

这是很久以前问的。但接受的答案不正确。

【讨论】:

    【解决方案2】:

    以下应该作为快捷方式:

    DateTime? temp = String.IsNullOrEmpty(row[10].ToString())? null : DateTime.Parse(temp0);
    

    【讨论】:

    • 我必须先转换语句的最后一段才能起作用。 d.date_migrate_prod = String.IsNullOrEmpty(row[10].ToString()) ? null : (DateTime?)DateTime.Parse(row[10].ToString()); ......我还没有弄清楚如何让 System.DBNull 工作呢
    • 目前,这可行(在我的评论中),所以我将其标记为答案。如果有人想帮助解决根本原因,我会测试你的答案。
    【解决方案3】:

    对所述问题的回答。

    string temp0 = row[10].ToString();
    DateTime?;
    if (string.IsNullOrEmpty(temp0)) 
    {
        temp = null;
    }
    else
    {
        temp = DateTime.Parse(temp0);
    }
    

    可以使用 DateTimeTryParse。
    可以传递一个空值,但它会解析为 1/1/0001

    【讨论】:

      【解决方案4】:

      试试:

      DateTime? localvariable 
            = row[10] == Convert.DBNull ? null : Convert.ToDateTime(row[10].ToString())
      

      【讨论】:

      • '@010001100110000101110010011010' 重新回答:尝试 localvariable = row[10] == Convert.DBNull ? null : row[10].ToString() ....... GETTING ERROR: 无法将类型 'string 隐式转换为 'System.DateTime?'
      • 我的错:日期时间? localvariable = row[10] == Convert.DBNull ? null : Convert.ToDateTime(row[10].ToString())
      猜你喜欢
      • 2013-04-01
      • 1970-01-01
      • 2017-06-27
      • 2011-05-18
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多