2011-03-08 158 views
0

有一個表類別(ID,標題,說明,parentID,friendlyUrl,categoryTypeID)。 字段值parentID可以爲null。如何選擇僅有的行 parentID = null如果@ParentID = null。sql查詢無法正常工作

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的空第一部分是真實的,因爲OR語句布爾邏輯的第二部分是不再重要,而忽視。

即AdaTheDev的回答將爲@ID工作@ParentID的原因,你需要:

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

這就是我需要的。 – Alexandre 2011-03-08 10:29:10

+1

+1刪除我的答案,因爲我錯誤地解決了它的錯誤領域:) – AdaTheDev 2011-03-08 11:01:51

+1

嗯,真的應該爲所有領域完成,因爲我期望這是它是如何工作的。 – 2011-03-08 12:08:12

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])