【问题标题】:SQL - Insert NULL into DateTimeSQL - 将 NULL 插入 DateTime
【发布时间】:2011-03-19 13:44:04
【问题描述】:

我有一个表,我在其中将Datetime 添加到某些列中。我使用存储过程将值插入表中。在存储过程中,我有接受 null 以插入表中的变量。我的问题是当我尝试在我的表列中插入一个空值时,我在列中得到 1900-01-01。我该怎么做而不是在列中只插入 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。

我该怎么办?

【问题讨论】:

  • 列InsertDate是否在表定义中指定了默认值?
  • @Brook:这将是一个很好的答案!
  • InsertDate 既可以是 null 也可以是有效日期。

标签: c# sql sql-server


【解决方案1】:

我正在使用这种模式,并且我对 null 或不兼容的文本格式没有任何问题。

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

【讨论】:

    【解决方案2】:

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

    话虽如此,代码应该仍然可以工作。你如何读取数据库?一些查看器将1900-01-01 显示为null。从 SQL Server Management Studio 运行 select * from Tables 时会看到什么?

    【讨论】:

    • 我使用数据源将表中的所有值读入 DataGridView。
    • @Man1:那么,如果您查看 SQL Server Management Studio 中的表,您会看到什么?还是在 Visial Studio 的“服务器资源管理器”中?
    • @Man1:select isnullable from syscolumns where name = 'InsertDate' and id = object_id('Tables') 返回什么?
    • @Man1: 好的...当你用if(true) 替换if (InsertDate.Text == "") 会发生什么?
    • @Main1:select definition from sys.default_constraints dc join sys.columns c on dc.parent_column_id = c.column_id and dc.parent_object_id = c.object_id where c.name = 'InsertDate' and c.object_id = object_id('Tables') 返回什么?
    【解决方案3】:

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

    大声笑,刚刚看到了 Addomar 的答案,如果 SSMS 中的列实际上不是 null,而是实际上为零,并且您无法更改数据库架构(有时这是不可能的),那么下面的方法将起作用...

    您可以尝试使用类似datacolumn datagridview replace specific value 的方法将值零替换为一些不同的文本或空白字符串?

    但理想情况下,将列更改为可空且不带默认值,并在应为空时省略参数。

    【讨论】:

    • 我知道替换特定值。但是必须有一种方法可以不将 1900-01-01 值添加到我的表中。
    【解决方案4】:

    我在 SSMS 中试过这个

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

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

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

    if (string.IsNullOrWhiteSpace(InsertDate.Text))
    

    而不是

    if (InsertDate.Text == "")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-01
      • 2017-08-26
      • 2015-07-21
      • 1970-01-01
      • 2014-04-25
      • 1970-01-01
      • 2020-04-15
      • 2011-08-30
      相关资源
      最近更新 更多