Insert NULL value in SQL Server

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?
 
M

Miha Markic [MVP C#]

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.
 
G

Guest

Try using a SqlDateTime.Null instead of DBNull.Value.


---

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

***************************
Think Outside the Box!
***************************
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top