我必须在不同的两种情况下选择不同的ItemID
。
在第一种情况下,我选择ItemID = @OrgID
作为组织父级,因为它们没有ParentOrganisationId
(为空) - 那么这种情况下工作正常。
我在第二种情况下遇到问题,我正在检查它是否是一个分支,然后使用子查询ParentOrganisationId
将= ItemID带入第一个where条件。第二种情况获得空值。
Declare @OrgID int
Set @OrgID = 91702 --- 91702(Branch Organisation), 83279(Parent Organisation)
select ItemID
FROM Organisations
where ItemID = case
when ParentOrganisationId is null
then @OrgID --case without branches
when ParentOrganisationId is not null
then (select ParentOrganisationId
from Organisations
where ItemID = @OrgID) --case with branches
end
答案 0 :(得分:4)
case
语句返回标量表达式,而不是列表。删除case
并使用基本布尔运算符表达逻辑:
select ItemID
FROM Organisations
where (ParentOrganisationId is null and ItemID = @OrgID) or
(ParentOrganisationId is not null and
ItemID in (select ParentOrganisationId from Organisations where ItemID = @OrgID)
);
答案 1 :(得分:0)
下次查询是否适合您?
select coalesce(ParentOrganisationId, ItemId) as ItemID
from Organisations
where ItemID = @OrdID