簡體   English   中英

從T-SQL返回NULL日期時間值到C#DataTable ==> DataRow中,而不是空字符串中

[英]Return NULL datetime value from T-SQL into C# DataTable ==> DataRow instead of empty string

此值(row [10])來自DataRow對象,來自T-SQL中的SQL結果集。 我相信它的類型是“對象”。 在我的數據庫中,對於此特定記錄,該字段的值為NULL,但它在結果集中返回一個空字符串,而不是空值。 我想解決根本問題,並讓我的結果集返回NULL而不是空字符串,但是如果那不可能,那么使此代碼更有效就可以了-意味着第一個代碼段,因為它適用於所有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;

這適用於null datetime值,實際datetime值,但不適用於row [10]等於空字符串的情況。

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

正確的方法是:

 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())
 }

為什么? 您不能在null上執行.ToString()。 然后,您需要進行點贊。 因此,將可空的DateTime更改為可空的DateTime。

這是很久以前問過的。 但是接受的答案是不正確的。

對所述問題的答案。

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

可以使用DateTimeTryParse。
可以傳遞null,但它將解析為1/1/0001

以下應作為快捷方式:

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

嘗試:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM