First of all, to insert null into the database column, the column must accept null s. Open the table in the designer and see if the corresponding column matches or not. If this is not the case and you try to insert a null value, you will receive an error message:
Cannot insert a NULL value in the column "InsertDate", table "TableName"; column does not allow null.
However, since you use stored procedures to insert data, I would recommend using the default values ββfor parameters at the procedure level, rather than burdening the application code. Then you can simply not set the parameter on the application side, and it will work correctly:
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
and on the C # side, just do:
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; }
Note that there is no else branch, so if InsertDate empty, the parameter is not sent at all.
Sweko
source share