2011-03-08 144 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])