我在 c#
中的 DataTable
中插入 Excel 工作表记录,并将此 DataTable 传递给 SQL 存储过程
。在我的 c# 代码中,我对 Excel 工作表的 empty
数据单元格进行了某些检查以避免异常。但似乎我在为我的 SQL Date
字段提供 default
值时遗漏了一些东西。
string InvoiceDate = (row.Cells[3].Text == " ") ? "0/00/0000 00:00:00 AM" : (row.Cells[3].Text);
我收到以下错误:
String was not recognized as a valid DateTime.Couldn't store <0/00/0000 00:00:00 AM> in InvoiceDate Column. Expected type is DateTime.
已编辑 - SQL字段声明[InvoiceDate]
[InvoiceDate] [date] NOT NULL
请不要建议插入 null
,因为我无法为该列插入 null
。
最佳答案
首先,没有00/00/0000
日期,在现实世界中不存在,在sql server中也不存在。
其次,为什么还需要默认值?只需使用 null 即可。
第三种,使用 ISO 8601 格式在字符串中指定日期 (yyyy-mm-ddThh:mm:ss
)
第四,如Giorgi在他的评论中正确地指出,为什么还要使用字符串作为日期时间值?使用 DateTime
类型的变量在 c#
中。请注意,它的最小值不同于 sql server DateTime
数据类型的最小值。
如果您的 datetime
列不可为空,您可以使用 1753-01-01
(日期时间的最小值)或 9999-12-31
(日期时间的最大值)
最后一件事,您可能要考虑使用 datetime2
或者将日期和时间分隔到不同的列(当然是数据类型 date
和 time
)。为什么? read here.
关于sql-server - 默认日期时间值应该是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30754260/