1

I wanted to learn which usage is true?

if(!string.IsNullOrEmpty(parentID))
   cmd.Parameters.Add(new SqlParameter("@ParentSesID", parentID));
else
   cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value));

OR

if(!string.IsNullOrEmpty(parentID))
   cmd.Parameters.Add(new SqlParameter("@ParentSesID", parentID));
else
   cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value.ToString()));

3 Answers 3

6
cmd.Parameters.Add(new SqlParameter("@ParentSesID", parentID));

This is passing a parentID to parameter @ParentSesID.

cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value));

is passing a null value to parameter.

cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value.ToString()));

is passing equal to string.Empty, which is not allowed in numerical data types.

cmd.Parameters.Add(new SqlParameter("@ParentSesID", null);

is same as ignoring the parameter.

So when you need to pass null to SP you've to pass DBNull.Value.

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

10 Comments

so DBNull.Value and null is not same?
@Sudhakar Nope, when you say null you're ignoring the parameter and DBNull says you're passing a null value to DB
so we can not pass null when table column is defined as not null right?
@Sudhakar When table is defined as not null you can't pass either null or DbNull both will fail
Okay, then when we will be using null instead of DBNull.Value? i think we should never use null then right?
|
2

This one: cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value)); is a correct, in case the field you are writing to can accept NULL value in database.

This one: cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value.ToString())); if the field is a, say, VARCHAR, and does not accept NULL, but you want to indicate in some way an absence of value in that field, so you write inside your application specific "no value" value. So your application knows, if it founds that value in the field, that means: no value.

Comments

1

DBNull.Value.ToString() will return empty string, so I think

cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value));

is a good approach and here the only approach

see here:

http://ideone.com/iGo1Jh

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.