I have an adjacency list in the DB and want to deliver the data in XML format to the client through a SQL SP. I\'m trying to use CTE and FOR XML but I am not getting the XM
The question as well as the OP's answer helped me a lot. It took me a bit to grasp the answer as I was missing some context. So here's a seperate answer with a more generic explanation (I've tried to remove every bit of code that didn't relate directly to getting hierarchical data in XML output).
Suppose the following typical table for hierarchical data:
CREATE TABLE Employee (Id INT, BossId INT, Name NVARCHAR(50));
Suppose it has the following data:
INSERT INTO Employee (Id, BossId, Name) VALUES
(1, NULL, 'Boss Pancone'),
(2, 1, 'Capioregime Luciano'),
(3, 1, 'Capioregime Bruno'),
(4, 2, 'Johnny'),
(5, 2, 'Luca'),
(6, 2, 'Luciano jr.'),
(7, 3, 'Marco'),
(8, 3, 'Mario'),
(9, 3, 'Giacomo');
To get hierarchical XML data we could use the following function:
ALTER FUNCTION dbo.fn_EmployeeHierarchyNode (@BossId INT) RETURNS XML
BEGIN RETURN
(SELECT Id,
BossId,
Name,
dbo.fn_EmployeeHierarchyNode(Id)
FROM Employee
WHERE BossId = @BossId
FOR XML AUTO)
END;
Which can be called like this:
SELECT dbo.fn_EmployeeHierarchyNode(1)
Or, if you want the root node as well, like this:
SELECT Id,
BossId,
Name,
dbo.fn_EmployeeHierarchyNode(Id)
FROM Employee
WHERE BossId IS NULL
FOR XML AUTO
Which would produce: