2
Ado.net의 매개 변수를 사용하여 where 절에 가능한 null 값을 사용하여 Sql 명령을 설정해야하는 이유는 무엇입니까?ado.net의 where 절에 null 값 매개 변수
SQL 문을 :
Select * from ViewSessionTarget where AgentId = @Parameter
Ado.net 코드
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"]);
}
}
결과 집합은 항상 내가 널 값을 가지고 있기 때문에 내 where 절에, 0 요소가됩니다. 그래서 등호 (=)가 작동하지 않고 "is"를 사용해야합니다. 나는이 내 SQL을 변경하면
는하지만 :
Select * from ViewSessionTarget where AgentId is @Parameter
나는 SQLException이 나타납니다. "근처의 구문이 잘못을 '@parameter'"
AgentId가 Null을 허용하지 않는다고 가정하면 :'Where AgentId = COALESCE (@Parameter, AgentId)' –