How do I have to set up an Sql command with possible null values in the where clause with parameters in Ado.net.
Sql Statement:
Select * from ViewSessionTarget where AgentId = @Parameter
Ado.net code
using (SqlConnection connection = new SqlConnection(@"my connection string"))
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
var parameter = command.Parameters.AddWithValue("@Parameter", DBNull.Value);
parameter.DbType = DbType.Int64;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Debug.Write(reader["SessionId"]);
}
}
The Resultset will always have 0 elements, because in my where clause I have a null value. So the equal (=) will not work and I have to use "is".
But when I change my sql to this:
Select * from ViewSessionTarget where AgentId is @Parameter
I receive an SqlException: "Incorrect syntax near '@Parameter'."