views:

186

answers:

3

How to execute a stored procedure with a nullable parameter in c#?

EDIT:

Actually, I've written below code. As you can see, status parameter is a nullable value type. Is it correct? or not?

public void LoadAll(DataTable tb, int? status=null)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection())
            {
                connection.ConnectionString = this.connectionString;

                using (SqlCommand command = connection.CreateCommand())
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "USP_OrganizationChartSelect";
                    SqlCommandBuilder.DeriveParameters(command);
                    command.Parameters["@Status"].Value = status.HasValue ? status : null;
                    if (connection.State != ConnectionState.Open)
                        connection.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    tb.Clear();
                    adapter.Fill(tb);
                    adapter.Dispose();
                    adapter = null;
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Thanks

A: 

If the parameter is nullable, it must be a value type. Suppose you have an int nullable parameter, then you can pass it this way..

  int? nullableParam = null;
  nullableParam = 10; //set the value if any
  //Pass nullableParam to your sp call.
this. __curious_geek
use the GetValueOrDefault method of the nullable object or its default value.
VoodooChild
+1 Good point :)
odiseh
default value for an int = 0 not what we have suggested (null)
odiseh
+1  A: 

you can check the nullable value in your sp like below:

select * from table
where (code = @code or @code is null)

by this solution if @code be null then this condition will not apply.

masoud ramezani
I've done this in my SP.
odiseh
+3  A: 

You could try DBNull.Value instead of null or omit the parameter when the nullable has no value entirely.

eddiegroves
you mean that I should put Deriveparameter in an if block ?
odiseh
I havn't done a lot of work with SqlCommand and Datasets but I would suggest trying the if test like: if (status.HasValue) { command.Parameters["@Status"].Value = status }
eddiegroves
what you suggested (using DBNull.value) generates an error indicating that there is no implicit conversion between int? and DBNull,
odiseh
How about: command.Parameters["@Status"].Value = (object)status ?? DBNull.Value;
eddiegroves