Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a null variable to a SQL Stored Procedure from C#.net code

Im calling a SQL stored procedure from a piece of C#.net code:

SqlHelper.ExecuteDataset(sqlConnection, CommandType.StoredProcedure, STORED_PROC_NAME, sqlParameters); 

where the sqlParameters variable is defined as:

        SqlParameter[] sqlParameters = new SqlParameter[SQL_NUMBER_PARAMETERS];          Log.Logger.Debug(string.Format("Running proc: {0} ", STORED_PROC_NAME));          SqlParameters[0] = new SqlParameter("fieldID", SqlDbType.BigInt );         SqlParameters[0].Value = fieldID;         SqlParameters[0].Direction = ParameterDirection.Input; 

I need to now pass in another two parameters to this Stored Proc, (both are of type SqlDateTime), which are going to NULL in this case.

Thanks,

IN

like image 625
Irfy Avatar asked Jul 30 '09 15:07

Irfy


People also ask

Can you return a null value using a stored procedure?

If you try to return NULL from a stored procedure using the RETURN keyword, you will get a warning, and 0 is returned instead. If a procedure hits an error that requires it to terminate immediately, it will return NULL because it never gets to either the RETURN keyword or the end of the batch!

Is null parameter in SQL?

If you want a parameter that can filter by a certain value, but when you have no value in your parameter, SQL returns no results. When the parameter has no value, SQL interprets it as null in your code. Null means no value. You can fix this problem by adding a code to fix the null case.

Can we pass null as argument in C#?

Yes. There are two kinds of types in . NET: reference types and value types. References types (generally classes) are always referred to by references, so they support null without any extra work.


2 Answers

SqlParameters[1] = new SqlParameter("Date1", SqlDbType.SqlDateTime); SqlParameters[1].Value = DBNull.Value; SqlParameters[1].Direction = ParameterDirection.Input; 

...then copy for the second.

like image 192
Justin Niessner Avatar answered Sep 26 '22 07:09

Justin Niessner


Use DBNull.Value Better still, make your stored procedure parameters have defaults of NULL. Or use a Nullable<DateTime> parameter if the parameter will sometimes be a valid DateTime object

like image 29
Dan Diplo Avatar answered Sep 25 '22 07:09

Dan Diplo