Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this table

Id  ParentId
1     0
2     0
3     0
4     3
5     3
6     2


i want to create a stored procedure that retrieves Ids based on the input of the parent and it also should retrieve a new field that returns true or false if the Id has other Ids that consider it as a parent. What i mean is

if the input to my stored procedure is 0 then the result should be:
Id ParentId hasId
1    0      0 it's false cause there is no Id in table considers Id 1 as a parent
2    0      1  it's true because Id =6 considers  Id 2 as a parent
3    0      1  it's true because Id =4 and 5 considers Id 3 as a parent


What I have tried:

CREATEPROCEDURE [dbo].[GetIds]
	@ParentId int

  AS

  SELECT 
		Table.Id 
	       ,Table.ParentId

  FROM		Table

WHERE	 Table.ParentId = @ParentId 

RETURN 0


How to do the hasId logic?
Posted
Updated 2-May-20 10:22am

1 solution

What you need to do is to JOIN the table back onto itself.

Play around with this sample
SQL
DECLARE @Table TABLE (ID INT, ParentID INT)
INSERT @Table VALUES (1, 0), (2, 0), (3, 0), (4, 3), (5, 3), (6, 2)

DECLARE @ParentID INT = 0

SELECT    p.ID, p.ParentID, Matches = case count(c.ID) when 0 then 0 else 1 end
FROM      @Table P
FULL JOIN @Table c on p.id = c.parentID
WHERE     p.ParentID = @ParentID
GROUP BY  p.ID, p.ParentID
 
Share this answer
 
Comments
Member 14800672 2-May-20 16:41pm    
Thank you so much, i tried left join instead of full join and it worked as well. Which is better and did you use full join for a reason?
MadMyche 2-May-20 18:25pm    
Left Join would work as well; the Full was leftover from an earlier version of this
Maciej Los 4-May-20 15:34pm    
5ed!
MadMyche 4-May-20 18:13pm    
Thank You

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900