I’m sure this has a very simple answer I am not finding… I have a simple hierarchy in a database where each row has a ParentId. If ParentId IS NULL, then it’s a root element. I have the stored procedure:
CREATE PROCEDURE GetByParent @parentId int
AS BEGIN SELECT * FROM TABLE1 WHERE ParentId = @parentId END
It works fine if I send an integer, but if I send NULL it becomes ParentId = NULL, which doesn’t work in ANSI. I know there is COALESCE(@parentId, ParentId), but that returns all rows when @parentId IS NULL. I can do an IF ELSE statement and copy the query (one with = @parentId and the other with IS NULL), but I’m sure there’s a better way.
Handle the NULL case in a separate condition: