提问者:小点点

从T-SQL返回NULL datetime值到C#DataTable==>DataRow而不是空字符串


该值(行[10])来自DataRow对象,来自T-SQL中的SQL结果集。我相信它有一个类型“object”。在我的数据库中,对于这个特定的记录,这个字段的值为NULL,但它在结果集中返回的是空字符串,而不是NULL值。我想解决根问题,让结果集返回NULL而不是空字符串,但如果不可能的话,让这段代码更高效就行了--这意味着第一段代码,因为它适用于所有三种情况。

当行[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;

这对于null datetime值(实际datetime值)有效,但当行[10]等于空字符串时则无效。

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

共1个答案

匿名用户

以下方法可以作为一种捷径:

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