2011-03-08 8 views
0

테이블 범주 (ID, 제목, 설명, parentID, friendlyUrl, categoryTypeID)가 있습니다. 필드 값 parentID는 null 일 수 있습니다.SQL 쿼리가 제대로 작동하지 않습니다.

만있는 행을 선택하는 방법 @ParentID = null 인 경우 parentID = null입니다.

declare @ID int =null 
    declare @FriendlyUrl nvarchar(30) = null 
    declare @ParentID int = null 
    declare @CategoryTypeID int = 0 


    select * from Category 
    where 
    (@ID is null or ID = @ID) 
    and (@FriendlyUrl is null or [email protected]) 
    and (@ParentID is null or [email protected]) 
    and (@CategoryTypeID is null or [email protected]) 

이 쿼리는 parentID = @ ParentID 경우 @ParentID = 지정된 int 값을 (이 맞아)가 모든 행을 선택합니다.

그러나 @ParentID = null 인 경우 모두 개의 행을 선택합니다 (올바르지 않습니다).

답변

4

귀하의 오류가 여기에 있습니다 :

and (@ParentID is null or [email protected]) 

@ParentID가 == 그 equasion의 null의 첫 번째 부분은 사실이고 때문에 OR 문 부울 논리의 두 번째 부분의

더 이상 무시 중요하지 않습니다.

는 AdaTheDev의 대답은 @ParentID를 들어 @ID을 위해 작동 할 이유는 당신이 필요로하는지 :

and ((@ParentID is null AND ParentID is null) or (@ParentID not is null AND ParentID = @parentID)) 
+0

내가 필요한 것입니다. – Alexandre

+1

+1 실수로 잘못된 필드에 대한 해결로 내 대답을 제거했습니다 :) – AdaTheDev

+1

글쎄, 정말 그것이 모든 필드에 대해 수행되어야합니다, 그것이 어떻게 작동하도록되어있다. –

1

이 방법에 대해 ... 아니면 제가 제대로 질문을 이해하지 못했다?

select * from Category
where (@ID is null or ID = @ID)
and (@FriendlyUrl is null or [email protected])
and (NOT(@ParentID is null) or [email protected]) ' added NOT here and (@CategoryTypeID is null or [email protected])

관련 문제