2011-03-23 60 views
2

在我的查詢中,如果發生特定情況,我想在查詢中添加和子句。 見我的查詢的WHERE子句SQL條件AND子句?

1  and ps.dept=dept.deptid 

2  and ps.sdept=deptsub.deptid 

3  and 

4 if(ps.dept<>ps.sdept) 

5 begin 

6 deptsub.Parent=dept.deptid 

7 end 

8 and ps.deptcategory=deptcat.category 

在4我想,如果條件滿足,然後6應該在查詢其他以不這是怎麼possible.thanks!

回答

4

如何:

and ps.dept=dept.deptid 
and ps.sdept=deptsub.deptid 
and (ps.dept=ps.sdept or deptsub.Parent=dept.deptid) 
and ps.deptcategory=deptcat.category 
3

嘗試更換線4,5,6,7本:

deptsub.Parent = 
case when ps.dept <> ps.sdept then dept.deptid 
else deptsub.Parent 
end 

當你的條件滿足的情況下聲明將取代dept.deptid,否則將只是替補deptsub.parent - 這將總是= deptsub.parent

3
and ps.dept=dept.deptid 
and ps.sdept=deptsub.deptid 
and 
(
    ((ps.dept<>ps.sdept) and (deptsub.Parent=dept.deptid)) 
    or 
    (ps.dept = ps.sdept) 
) 
and ps.deptcategory=deptcat.category