2014-09-07 3 views
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'"

+1

AgentId가 Null을 허용하지 않는다고 가정하면 :'Where AgentId = COALESCE (@Parameter, AgentId)' –

답변

0

당신은 당신에게이 같은 SQL 쿼리 뭔가를 쓸 수 ...

Select * from ViewSessionTarget where AgentId = @Parameter OR @Parameter IS NULL 

또는 당신은 또한 당신에게 더 나은 성능, 같은 것을 제공 할 수 있습니다 약간의 프로 시저를 만들 수 있습니다 ....

CREATE PROCEDURE dbo.myProc 
@Parameter INT 
AS 
BEGIN 
    SET NOCOUNT ON; 
    DECLARE @Sql NVARCHAR(MAX); 

SET @Sql = N'Select * from ViewSessionTarget where 1 = 1 ' 
      + CASE WHEN @Parameter IS NOT NULL THEN 
       N'AND AgentId = @Parameter ' ELSE N' ' END 

EXECUTE sp_executesql @Sql 
        ,N'@Parameter INT ' 
        ,@Parameter     

END