2014-02-14 62 views
-1

我正在應用一個查詢,我需要爲單個部門或所有部門獲取結果。應用案例從SQL中獲取所有記錄

PersonID PersonName 
1   'Abc' 
2   'CDE' 
3   'xyz' 

DepartmentID DepartmentName 
1     'Accounts' 
2     'Finance' 

HirarchyID personID DepartmentID 
1    1  1 
2    1  1 
3    2  1 

現在我想在我的SQL查詢我有過爲1 = 'Accounts', 2='Finance' and 0 = 'Both'

我怎麼會在我的查詢應用此@department參數的參數?

我嘗試申請與案件,但它只會讓我或者帳戶或財務..但不是兩個。

select * from persons p join 
Hierarchy h on h.PersonID = p.PersonID JOIN 
Department d on d.DepartmentID = h.DepartmentID 
where case ??? 

我的樣品凡在我查詢子句是這樣的:

WHERE  (sa.Area in (case when @myMode = 1 THEN 'abc Mode' 
          when @myMode = 2 THEN 'XYZ Mode' 
          ELSE 
          'abc Mode,xyz Mode' 
          END)) 
+0

地方是查詢:

相反,如果你希望所有的部門,如下更改此行的代碼? – Jade

+0

這只是我試圖達到的一個例子..我的查詢是相當複雜的,有一個where子句,我需要應用這種情況 – Moiz

回答

1

反轉的條件由作爲in()的左手側供給變量:

select * from mytable 
where @department in (DepartmentID, 0) 
0
@DepartmentID is parameter that you are passing as "DepartmentID" 

If(@DepartmentID=1) 
begin 
    --your code 
    select * from Department where DepartmentID =1 
end 
else if(@DepartmentID=2) 
begin 

    --your code 
    select * from Department where DepartmentID =2 
end 
else if(@DepartmentID=0) 
begin 

    select * from Department where DepartmentID in(1,2) 

end 

我希望這會有所幫助....

+0

我該如何滿足3個條件? 1,2和0(全部) – Moiz

+0

請參閱@Bohemian答案,它的工作原理和優雅。 –

+0

如果我通過名字並且沒有ID,該怎麼辦? – Moiz

0

試試這個:

-- populate a temp table for demo purposes only 
select * 
into #departments 
from (
    select 1 as DepartmentId, 'Accounts' as DepartmentName 
    union all 
    select 2 as DepartmentId, 'Finance' as DepartmentName 
) as q1 

declare @deptName nvarchar(50) = 'Accounts'; 
declare @deptId int = coalesce((
    select DepartmentId 
    from #departments 
    where DepartmentName = @deptName 
),0); 

select * 
from #departments -- or dbo.someOtherTable ... which would make more sense 
where @deptId in(DepartmentId,0) 
go 

這將返回記錄僅Accounts部門。

declare @deptName nvarchar(50) = ''; 
0

嘗試用這種

SELECT person_table.* 
    FROM person_table  , 
    department_table , 
    heirarchy_table 
WHERE person_table.person_id  = heirarchy_table.person_id 
    AND department_table.department_id = heirarchy_table.department_id 
    AND department_table.department_id = CASE WHEN (:PASSEDPARM = '0') THEN department_table.department_id 
             ELSE :PASSEDPARM 
             END; 

DB2語法

相關問題