Hi!
I have this Table structure:
Id int not null --PK
Title varchar(50)
ParentId int null --FK to same Table.Id
I'm writing a SP that returns a row's "brothers", here's the code
select * from Table
where Table.ParentId = (select Table.ParentId from Table where Table.id = @Id)
and Table.Id <> @Id
It works perfectly for rows having a parent, but for those who's parent are null (root records), it returns no row. This is working as expected since null = null
is always false.
I'm looking for help on how to better design my SP to handle this specific case. I'm not a DBA and my TSQL knowledge is basic.
EDIT: I've updated my SQL query like this:
DECLARE @Id INT
SET @Id = 1
DECLARE @ParentId INT
SET @ParentId = (SELECT Table.ParentId FROM Table WHERE Table.Id = @Id)
SELECT * FROM Table
WHERE (
(@ParentId IS NULL AND (Table.ParentId IS NULL))
OR (Table.ParentId = @ParentId)
)
AND Table.Id <> @Id
It does do the job but if the Id is not in the table, it still returns the row who have no parents. Going to lunch, continue looking at this later.
Thanks in advance, Fabian