SQL developers, I have a badly planned database as task to learn a lot about SQL Server 2012.
SO, there is the table Elem
:
+-----------+----
I've created a function for finding the parents of a specific child where you have to pass the Id of the child.
This will return the list of parents as a comma separated string. Try this if it works for you.
I'm assuming that the parent_key with null value
is root.
CREATE FUNCTION checkParent(@childId INT)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @parentId VARCHAR(MAX) = NULL
DECLARE @parentKey INT = null
SET @parentId = (SELECT parent_key FROM Elem WHERE [KEY] = @childId)
WHILE(@parentKey IS NOT NULL)
begin
SET @parentId = @parentId + ', ' + (SELECT parent_key FROM Elem WHERE [KEY] = @parentId)
SET @parentKey = (SELECT parent_key FROM Elem WHERE [KEY] = @parentId)
END
RETURN @parentId
END
GO