将非空日期时间转换为空。 C#
Posted
技术标签:
【中文标题】将非空日期时间转换为空。 C#【英文标题】:To convert not null datetime into null. c# 【发布时间】:2020-12-03 22:27:09 【问题描述】:当我对整个表进行求和时,我想让我的非空 DateTime
列 null
不为空,这样我就不会得到日期时间 1/1/0001 12:00:00
的任何值。我想在这个方法中添加任何可能的语句。我尝试解析它,但它不起作用,但对于 Amount
来说完全没问题。
private void SumOfRecords_Button(object sender, RoutedEventArgs e)
ObservableCollection<Receipt> receipts = new ReceiptDAO().GetAllReceiptsFromPiName();
Receipt receipt = new Receipt();
if (receipt.DateTime != null)
Receipt receipt0 = new Receipt()
DateTime = DateTime.TryParse(),
Amount = new ReceiptDAO().SumOfRecords("Amount")
;
receipts.Add(receipt);
this.Dispatcher.Invoke(() => ReceiptList.ItemsSource = receipts);
这是我正在编写查询的SumOfRecords
的方法。
public double SumOfRecords(string columnName)
ObservableCollection<Receipt> receipts = new ReceiptDAO().GetAllReceiptsFromPiName();
Receipt receipt = new Receipt();
string commandstring;
commandstring = "select Sum(" + columnName + ") from " + getTable();
using (SQLiteConnection connection = ConnectToDatabase())
using (SQLiteCommand command = new SQLiteCommand(commandstring, connection))
using (SQLiteDataReader reader = command.ExecuteReader())
reader.Read();
return reader.GetDouble(0);
【问题讨论】:
SumOfRecords
中有什么内容?
拥有minimal reproducible example 会很棒。
我刚刚添加了 SumOfRecords 方法中的内容。
Why is concatenating SQL strings a bad idea?
【参考方案1】:
在计算总和时忽略日期。假设您使用 sql server 作为数据库。
var where = " WHERE Table.Date <> '0001/01/01 00:00:00'";
commandstring = "select Sum(" + columnName + ") from " + getTable() + where;
您可以将where
作为参数传递给该方法以使其可重用。根据您使用的数据库,您可能需要查看日期比较。否则,概念保持不变。
【讨论】:
以上是关于将非空日期时间转换为空。 C#的主要内容,如果未能解决你的问题,请参考以下文章
flask-sqlalchemy中的日期查询在相等时为空,在ge或le时为非空
将 C# DateTime 转换为 Javascript 日期