SQL 服务器查询 select 情况下

SQL Server Query select case when

我必须 select 在不同的两种情况下 ItemID

在第一种情况下,我 selecting 作为组织父级的 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

case 语句 returns 标量表达式,而不是列表。删除 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)
      );

下一个查询不适合您吗?

select coalesce(ParentOrganisationId, ItemId) as ItemID
from Organisations
where ItemID = @OrdID