我正在应用一个查询,我需要获得单个部门或所有部门的结果。
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子句是这样的:
WHERE (sa.Area in (case when @myMode = 1 THEN 'abc Mode'
when @myMode = 2 THEN 'XYZ Mode'
ELSE
'abc Mode,xyz Mode'
END))
答案 0 :(得分:1)
通过将变量作为in()
:
select * from mytable
where @department in (DepartmentID, 0)
答案 1 :(得分: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
我希望这会有所帮助......
答案 2 :(得分: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) = '';
答案 3 :(得分: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语法