Before anyone comments that this has been answered before in other question I KNOW that..but in spite of the answers I have reviewed at
- Assign null to a SqlParameter
- Sending null parameters to Sql Server
- Best method of assigning NULL value to SqlParameter
and even my own question at
I am unable to get my query to return values with null parameters
I have tried simplifying my code so it can be seen here.
I have also tried this with
int? i = null;
SqlConnection connection = new SqlConnection(Properties.Settings.Default.connstring.ToString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "Select * from view_nests where parent_pk = @parent_pk";
cmd.Parameters.AddWithValue("@parent_pk", i ?? Convert.DBNull);
cmd.Connection.Open();
var dataReader = cmd.ExecuteReader();
var dataTable = new DataTable();
dataTable.Load(dataReader);
cmd.Connection.Close();
I have tried variations on this where I just did
cmd.Parameters.AddWithValue("@parent_pk", DBNull.Value);
And I have tried using the query
cmd.CommandText = "Select * from view_nests where parent_pk = @parent_pk or @parent_pk Is Null";
I tried explicitly declaring the parameter as nullable
cmd.Parameters.AddWithValue("@parent_pk", i ?? Convert.DBNull).IsNullable = true;
Which for some reason I thought I had working hence my reason for accepting the answer I did but I was mistaken that just returns everything to me no matter what the value.
I know the command object is connecting and returns data because if I put in a valid value (say 27) it returns the record...I also know that there are records with Null as the value...but no matter how I try to set it up I keep getting nothing returns when I try to pass a null value as the parameter.
Anyone who can help me figure out what I'm doing wrong here I would be grateful.