如何在sql server中的datetime类型列中插入null
本文关键字:类型 插入 null datetime 中的 sql server | 更新日期: 2023-09-27 18:26:39
我有一个表,其中有一些日期时间类型的列。我使用存储过程将值插入到表中。在存储过程中,我有一些变量接受null以插入到表中。我的问题是,当我试图在表的datetime列中插入一个null值时,它会引发错误。我的代码是.
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;
}
cmd1.Parameters["@InsertDate"].Value = getDate ?? DBNull.Value;
键是DBNull.Value。我想您有一个可以为null的DateTime变量,即DateTime? someVariable
。您可以测试它是否为null,如果是,则使用DBNull.Value
(如上所示)。
if (//some condition)
{
cmd.Parameters.AddWithValue("@dateofBirth", txtdob.text);
}
else
{
cmd.Parameters.AddWithValue("@dateofBirth", DBNull.Value);
}
要将null值传递给db,可以使用DBNull.value。请尝试此
if (string.IsNullOrWhiteSpace(InsertDate.Text))
{
cmd1.Parameters["@InsertDate"].Value =DBNull.Value;
}
else
{
cmd1.Parameters["@InsertDate"].Value = InsertDate.Text;
}
尝试使用此
System.Data.SqlTypes.SqlDateTime.Null
首先,要能够将null
插入数据库列,该列必须接受null
s。在设计器中打开表,查看相关列是否可以为null。如果不是,并且您尝试插入一个空值,您将得到错误:
无法在表"TableName"的"InsertDate"列中插入值NULL;列不允许为null。
也就是说,由于您使用存储过程来插入数据,我建议在过程级别上使用参数的默认值,而不是加重应用程序代码的负担。然后,你可以不在应用程序端设置参数,它就会正常工作:
create procedure InsertIntoTable
-- ....other parameters here...
@InsertDate datetime = null -- this means that if the value is not supplied,
-- null is used by default
as begin
insert into TableName (InsertDate) values (@InsertDate)
end
在C#方面,只需执行:
if (!string.IsNullOrWhitespace(InsertDate.Text)) {
// check to see if the entered text is actually a date
DateTime insertDate = ... some parsing/verification code...;
cmd1.Parameters["@InsertDate"].Value = insertDate;
}
请注意,没有else
分支,因此如果InsertDate
为空,则根本不发送参数。
尝试这样的操作,使用Add而不是AddWithValue。。
DB.Parameters.Add("@date", SqlDbType.DateTime).Value = DBNull.Value;
您应该能够直接提供null
作为参数值:
if (String.IsNullOrWhitespace(InsertDate.Text)) {
cmd1.Parameters["@InsertDate"].Value = null;
} else {
cmd1.Parameters["@InsertDate"].Value = InsertDate.Text;
}
还切换到使用String.IsNullOrWhitespace()
来检查空字符串。
尝试使用:
if (string.IsNullOrWhiteSpace(InsertDate.Text))
{
cmd1.Parameters["@InsertDate"].Value = getDate;
}
else
{
cmd1.Parameters["@InsertDate"].Value = InsertDate.Text;
}
在存储过程中执行以下操作:
insert into table(date)
values(case when @InsertDate ='' then
null
else
@insertDate
end)
如果DBNull.Value不起作用,请尝试此逻辑。。使用DateTime?空
确保您的数据库字段应允许空
dtexpiry=无效的dtexpiry:(DateTime?)空
您可以使用它。我没有捷径!!
if(InsertDate.Text==")cmd。参数.AddWithValue("@enddate",DBNull.Value);其他的cmd。参数.AddWithValue("@enddate",转换.ToDateTime(InsertDate.Text));