SQL Server Query选择大小写时的情况

时间:2015-02-25 11:52:40

标签: sql sql-server sql-server-2008

我必须在不同的两种情况下选择不同的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

2 个答案:

答案 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