问题 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。

我该怎么办?


9023
2018-03-19 13:44


起源

是专栏吗? InsertDate 是否在表定义中指定了默认值? - Brook
@Brook:那将是一个很好的答案! - Andomar
InsertDate既可以为null,也可以是有效日期。 - Man1


答案:


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

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;
}

5
2018-03-19 14:47





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

话虽如此,代码应该仍然有用。你怎么看数据库?一些观众显示 1900-01-01 对于 null。你跑步时看到了什么 select * from Tables 从SQL Server Management Studio?


3
2018-03-19 13:48



我使用数据源将表中的所有值读入DataGridView。 - Man1
你的意思是SP参数? - Man1
@ Man1:那么如果你看一下SQL Server Management Studio中的表,你会看到什么?或者在Visial Studio的“服务器资源管理器”中? - Andomar
@ Man1:有什么用 select isnullable from syscolumns where name = 'InsertDate' and id = object_id('Tables') 返回? - Andomar
赞成极好的调查技巧:) - Rich Andrews


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

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

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

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


2
2018-03-19 14:09



我知道替换特定值。但必须有办法不将1900-01-01的价值放在我的桌子上。 - Man1


我在SSMS中试过这个

declare @InsertDate datetime

set @InsertDate = '   '

select @InsertDate

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

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

if (string.IsNullOrWhiteSpace(InsertDate.Text))

代替

if (InsertDate.Text == "")

1
2018-03-19 14:24