SQL – 将NULL插入DateTime

我有一个表格,我将Datetime添加到某些列。 我使用存储过程将值插入表中。 在存储过程中,我有变量接受null以插入表中。 我的问题是当我尝试在我的表列中插入一个空值时,我在列中得到1900-01-01。 我该怎么做而不是这个默认值只插入colulmn中的NULL?

这是我的SP:

 CREATE PROCEDURE dbo.Insert @InserID int, @InsertDate Datetime = null, AS Insert into Tables(InsertID, InsertDate) Values(@InsertID, @InsertDate) 

我这样做是为了分配一个空值:

 System.Data.SqlTypes.SqlDateTime getDate; //set DateTime null getDate = SqlDateTime.Null; if (InsertDate.Text == "") { cmd1.Parameters["@InsertDate"].Value = getDate; } else { cmd1.Parameters["@InsertDate"].Value = InsertDate.Text; } 

添加到我的表列的值不是NULL,它是1900-01-01。

我该怎么办?

我正在使用这种模式,我没有空值或不兼容的文本格式的问题。

 cmd1.Parameters.Add["@InsertDate"].Value = textBox1.Text.AsDBDateTime(); // ... public static class DBValueExtensions { public static object AsDBDateTime(this string s) { object dateTimeValue; var str = s; if ( null != str ) { str = str.Trim(); } if ( string.IsNullOrEmpty(str) ) { dateTimeValue = DBNull.Value; } else { dateTimeValue = DateTime.Parse(str); } return dateTimeValue; } 

您可以完全省略可选参数,而不是将它们设置为SqlDateTime.Null

话虽如此,代码应该仍然有用。 你怎么看数据库? 某些观看者显示1900-01-01null 。 从SQL Server Management Studio中运行select * from Tables时,您看到了什么?

我怀疑你的日期有一个从DBNull隐式转换为0,因为默认情况下DateTime不可为空。 这将重现您所看到的行为。

大声笑,刚刚看到Addomar的答案,如果SSMS中的列实际上不是null但实际上是零并且你不能改变数据库模式(有时这是不可能的)那么下面的方法将起作用…

您可以尝试像datacolumn datagridview替换特定值 ,用一些不同的文本或空字符串替换零值?

但理想情况下,将列更改为可为空而没有默认值,并在应该为null时省略该参数。

我在SSMS中试过这个

 declare @InsertDate datetime set @InsertDate = ' ' select @InsertDate 

返回1900-01-01 00:00:00.000

所以另一种可能性是你的输入是空格。 尝试使用

 if (string.IsNullOrWhiteSpace(InsertDate.Text)) 

代替

 if (InsertDate.Text == "")