返回从T-SQL NULL datetime值转换为C#的DataTable ==> DataRow的,而不是空字符串转换为、而不是、空字符串、NULL

2023-09-05 04:20:54 作者:掐死你的温柔

该值(行[10])是由DataRow对象来了,从SQL结果在T-SQL设置。我相信它有一种类型的对象。在我的数据库,我有NULL该字段为这个特殊的记录中的值,但它返回一个空字符串我的结果集,而不是一个空值。我想解决一个空字符串的根本问题,并有我的结果集返回NULL代替,但如果这是不可能的,这使得code更有效的将是就好了 - 这意味着第一个片段,因为它的工作原理所有3例。

这工作时,行[10]的ToString()等于空字符串,null或datetime格式,但我想将它缩短。这是我的解决办法了。的

 字符串TEMP0 =行[10]的ToString();
        日期时间? TEMP = NULL;
        如果(TEMP0 ==)
        {
            TEMP0 = NULL;
        }
        如果(TEMP0!= NULL)
        {
            临时= DateTime.Parse(TEMP0);
        }

        d.date_migrate_prod =气温== NULL?空:温度;
 

这适用于空datetime值,实际的日期时间值,而不是当行[10]等于空字符串。的

 日期时间?临时= DateTime.Parse(行[10]的ToString());
        d.date_migrate_prod =气温== NULL?空:温度;
 
sql查询null的3种方式的区别

解决方案

下面应该作为一种快捷方式:

 日期时间?临时= String.IsNullOrEmpty(行[10]的ToString())?空:DateTime.Parse(TEMP0);
 

This value (row[10]) is coming from a DataRow object, from a SQL result set in T-SQL. I believe it has a type "object". In my database, I have a value of NULL for this field for this particular record, but it's returning an empty string in my result set, not a null value. I'd like to fix the root problem and have my result set return NULL instead of an empty string, but if that's not possible, making this code more efficient would be just fine--meaning the 1st snippet, since it works for all 3 cases.

This works when row[10].ToString() is equal to an empty string, null or a DateTime format, but I'd like to shorten it. This is my workaround for now.

        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;

This works for a null datetime value, an actual datetime value, but not when row[10] is equal to an empty string.

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

解决方案

The following should work as a shortcut:

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