How to insert null in datetime type column in sql server

后端 未结 11 2135
醉酒成梦
醉酒成梦 2021-02-20 15:23

I have a table in which there are some datetime type columns. I use a stored procedure to insert values into the table. In the stored procedure I have variables that accept null

11条回答
  •  借酒劲吻你
    2021-02-20 16:07

    First of all, to be able to insert null into a database column, the column must accept nulls. Open the table in the designer, and see if the relevant column is nullable or not. If it's not and you try to insert a null value, you'll get the error:

    Cannot insert the value NULL into column 'InsertDate', table 'TableName'; column does not allow nulls.

    That said, since you are using stored procedures to insert data, I would recommend using default values for the parameters on the procedure level, instead of burdening the aplication code. Than, you can just not set the parameter on the application side, and it would 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 the InsertDate is empty, the parameter is not sent at all.

提交回复
热议问题