[英]How to insert null in datetime type column in sql server
我有一個表,其中有一些日期時間類型的列。 我使用存儲過程將值插入表中。 在存儲過程中,我有一些變量接受 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。 我想你有一個可為空的 DateTime 變量,即DateTime? someVariable
DateTime? someVariable
。 您可以測試它是否為空,如果是使用DBNull.Value
(如上所示)。
if (//some condition)
{
cmd.Parameters.AddWithValue("@dateofBirth", txtdob.text);
}
else
{
cmd.Parameters.AddWithValue("@dateofBirth", DBNull.Value);
}
要將空值傳遞給 db,您可以使用 DBNull.Value。 請試試這個
if (string.IsNullOrWhiteSpace(InsertDate.Text))
{
cmd1.Parameters["@InsertDate"].Value =DBNull.Value;
}
else
{
cmd1.Parameters["@InsertDate"].Value = InsertDate.Text;
}
首先,為了能夠將null
插入到數據庫列中,該列必須接受null
s。 在設計器中打開表,查看相關列是否可以為空。 如果不是,並且您嘗試插入空值,則會收到錯誤消息:
無法將值 NULL 插入列 'InsertDate'、表 'TableName'; 列不允許空值。
也就是說,由於您使用存儲過程來插入數據,我建議在過程級別為參數使用默認值,而不是增加應用程序代碼的負擔。 比,你不能在應用程序端設置參數,它會正常工作:
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
為空,則根本不發送參數。
嘗試使用這個
System.Data.SqlTypes.SqlDateTime.Null
嘗試這樣的事情,使用 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()
來檢查空字符串。
在存儲過程中做這樣的事情:
insert into table(date)
values(case when @InsertDate ='' then
null
else
@insertDate
end)
嘗試使用:
if (string.IsNullOrWhiteSpace(InsertDate.Text))
{
cmd1.Parameters["@InsertDate"].Value = getDate;
}
else
{
cmd1.Parameters["@InsertDate"].Value = InsertDate.Text;
}
如果 DBNull.Value 不起作用,請嘗試此邏輯.. 使用 DateTime? 無效的
確保您的數據庫字段應允許為空
dtexpiry!=空? dtexpiry :(日期時間?)空
你可以用這個。 我沒有捷徑!!
if (InsertDate.Text == "") cmd.Parameters.AddWithValue("@enddate", DBNull.Value ); 否則 cmd.Parameters.AddWithValue("@enddate", Convert.ToDateTime(InsertDate.Text) );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.