Insert NULL value in SQL Server

  • Thread starter Thread starter Dinko Deranja
  • Start date Start date
D

Dinko Deranja

I have the following statement (mycommand is SQLClient.SQLCommand):

mycommand.commandtext = "INSERT INTO myTable (mysmalldatetime) VALUES
(@mysmalldatetime)"
mycommand.Parameters.Add("@mysmalldatetime", SQLDBType.SmallDateTime,
4).Value = IIf (startDate.Text <> "", startDate.Text, DBNull.Value)

If user enters startDate in textbox then it works, but if the textbox is
empty, then the error message says (at mycommand.executenonquery()):
Input string was not in a correct format.

The question is - how to insert the null value in this smalldatetime field?
 
Hi,

Your code is probably still using first branch (startDate.Text).
DBNull.Value is correct value for inserting null values.
I strongy suggest you to check the startDate.Text value (IIF is branching in
the wrong direction) when you think you should pass null value.
 
Try using a SqlDateTime.Null instead of DBNull.Value.


---

Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

***************************
Think Outside the Box!
***************************
 
Back
Top