1

I would like to add some null's to table:

command.CommandText =
"INSERT into clients (Addres, companyID) VALUES (@Addres, @companyID) ; select SCOPE_IDENTITY();";
command.Parameters.AddWithValue("@Addres", null);
command.Parameters.AddWithValue("@companyID", null);

Table dessign allows null's. Why I have this error then?

The parameterized query '(@Addres nvarchar(4000),@companyID nvarchar(4000))INSERT into cl' expects the parameter '@Addres', which was not supplied.

3 Answers 3

4

Use DBNull.Value instead.

command.Parameters.AddWithValue("@Addres", DBNull.Value);
command.Parameters.AddWithValue("@companyID", DBNull.Value);
Sign up to request clarification or add additional context in comments.

1 Comment

2

You have to use DBNull class for null values in SQL. Your code will be like this:

command.Parameters.AddWithValue("@Addres", DBNull.Value);
command.Parameters.AddWithValue("@companyID", DBNull.Value);

Comments

2

You can use System.Data.SqlTypes.SqlString.Null

command.Parameters.AddWithValue("@Addres", System.Data.SqlTypes.SqlString.Null);
command.Parameters.AddWithValue("@companyID", System.Data.SqlTypes.SqlString.Null);

Read: Handling Null Values

DBNull.Value can be used for any type as opposed to SqlTypes.

It can be handy to make the code more readable and type-safe, for example:

var addrVal = new System.Data.SqlTypes.SqlString(someAddress);
// ...
if (condition) addrVal = System.Data.SqlTypes.SqlString.Null;
command.Parameters.AddWithValue("@Addres", addrVal);

3 Comments

What if the parameter is not a string?
@ThorstenDittmar: but in this case it is a string, both are nvarchar, that's why i have used it. If it's an int(for example): SqlInt32.Null. It's the "type safe" version.
I just wanted to have that mentioned :-D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.