0

How to set Default Value as Value of SqlCommand SqlParameter?

SqlCommand is the class contained in System.Data.SqlClient

My Schema does not accept DBNull.Value as value

SqlCommand command = new SqlCommand();
command.Parameters.Add(new SqlParameter("column_1", SqlDbType.VarChar, 1) { Value = DBNull.Value });

2 Answers 2

3

As lboshuizen points out, if your "schema" isn't taking null, or the parameter of the stored procedure or query cannot be null, trying to give it a null value will likely fail. In this case, you need to see why you are trying to set it to null if you know it doesn't accept it. I would surmise an empty string as opposed to null would work, or something else that is sensible.

The SqlParameterCollection property Parameters has an AddWithValue method:

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx

You can simply insert null and that will be handled for you:

command.Parameters.AddWithValue("@parameter", null);

If you cannot provide a null, you can provide something like an empty string:

command.Parameters.AddWithvalue("@parameter", "");

You also very rarely need to specify the data type using this mechanism.

Sign up to request clarification or add additional context in comments.

5 Comments

@lboshuizen In that case he cannot pass null or DBNull.Value and one wonders why he is trying.
He wants to provide a default to avoid the dbnull
Ok using your second option works, but' there is nothing like DBnull.Value for Default? Something like DBdefault.Value ? I'm dreaming?
@andrea If the column doesn't take nulls then that won't work.
command.Parameters.AddWithvalue("@parameter", ""); this has worked
1

If the schema doesn't accept null it indicates that the column is mandatory and requires a sensible value.

Using a default value for a column is a property of the schema.

  1. So either alter the schema to provide a default. ALTER TABLE {TABLENAME} ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
  2. Choose a valid (not null) default value in your application code and use it as a value in the parameter. const string default = "unknown"; ... SqlCommand command = new SqlCommand(); command.Parameters.Add(new SqlParameter("column_1", SqlDbType.VarChar, 1) { Value = default });

Note: Changing the schema to accept NULL is considered cheating :-)

Comments

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.