Sql server SP:处理空值

Sql server SP:处理空值,sql-server,stored-procedures,Sql Server,Stored Procedures,我有以下表格结构: Id int not null --PK Title varchar(50) ParentId int null --FK to same Table.Id 我正在编写一个返回一行兄弟的SP,下面是代码 select * from Table where Table.ParentId = (select Table.ParentId from Table where Table.id = @Id) and Table.Id <> @Id 它确实执行此任务,但如

我有以下表格结构:

Id int not null --PK
Title varchar(50)
ParentId int null --FK to same Table.Id
我正在编写一个返回一行兄弟的SP,下面是代码

select * from Table
where Table.ParentId = (select Table.ParentId from Table where Table.id = @Id)
and Table.Id <> @Id
它确实执行此任务,但如果Id不在表中,它仍然返回没有父项的行。去吃午饭,以后继续看这个

提前感谢,,
Fabian

我不确定这是否是最佳解决方案,但您可以尝试使用无效id表示NULL的运算符

select * from Table
where COALESCE(Table.ParentId,-1) = (select COALESCE(Table.ParentId,-1) from Table where Table.id = @Id)
and Table.Id <> @Id

假设-1从未用作ID,我可能不理解您的问题描述,但是,为了仅在给定父级存在兄弟时返回兄弟,以下查询应该足够了:

  select Brother.* 
    from Table Parent
        inner join Table Brother on
          Parent.id = Brother.ParentID
    where Parent.Id= @Id and Brother.Id <> @Id

这不是sargable,尽管它只适用于小表。很好的解决方案,它可以工作,并且我的表将永远不会有超过200条记录。您是否仍将在此处使用NULL进行相等操作Parent.id=Brother.ParentID?@Martin Smith:Parent.id=NULL不应返回兄弟记录,我认为这是理想的结果?我的解释是,所有具有空ParentID值的记录都应该被视为兄弟。我想在这种情况下,使用sentinel ParentID值0或其他值可能比使用NULL更容易获得所需的相等语义。@Martin,我不能,因为链接会自动解析以构建对象的层次图。我认为我的上一次编辑是一个很好的解决方案,仍然需要解决一个问题。@Martin Smith:啊,好的。。。那么所有具有空ParentID的兄弟都将被视为自己的集合?从data domain定义的角度来看,这有点顽皮,但正如您所建议的,sentinel值可以提供解决方案
  select Brother.* 
    from Table Parent
        inner join Table Brother on
          Parent.id = Brother.ParentID
    where Parent.Id= @Id and Brother.Id <> @Id