SQL - 将NULL插入DateTime

Man*_*an1 11 c# sql sql-server

我有一个表格,我添加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)
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

我该怎么办?

TcK*_*cKs 5

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

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;
}
Run Code Online (Sandbox Code Playgroud)


And*_*mar 3

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

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