## http://stackoverflow.com/questions/9577122/select-parent-and-its-children-with-sqlserver

0

(click on this box to dismiss)

Q&A for active researchers, academics and students of physics

SET NOCOUNT ON;
DECLARE @Messages AS TABLE (ID INT NOT NULL, Description VARCHAR(MAX) NOT NULL);
DECLARE @Comments AS TABLE (ID INT NOT NULL, MessageID INT NOT NULL, Body VARCHAR(MAX) NOT NULL);

INSERT INTO @Messages
VALUES (1, 'Message 1'),
(2, 'Message 2'),
(3, 'Message 3'),
(4, 'Message 4'),
(5, 'Message 5'),
(6, 'Message 6'),
(7, 'Message 7'),
(8, 'Message 8'),
(9, 'Message 9'),
(10, 'Message 10'),
(11, 'Message 11'),
(12, 'Message 12'),
(13, 'Message 13');

SELECT ROW_NUMBER() OVER(ORDER BY msg.ID, Numbers.num)
, msg.ID
, msg.Description + ':Commment ' + CONVERT(varchar(max), Numbers.num)
FROM @Messages msg
CROSS JOIN (SELECT 1 AS num UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) AS Numbers;

-- SELECT * FROM @Messages;

SELECT STUFF(Z.Messages, 1, 2, '') FROM (
SELECT ', ' + MessageWComments FROM (
SELECT TOP 10 '"Message": "' + msg.Description + '", "Comments": [ ' + STUFF(X.Comments, 1, 2, '') + ' ]' AS MessageWComments
FROM @Messages msg
OUTER APPLY (
SELECT TOP 3 ', { "text" : "' + Body + '" }'
WHERE MessageID = msg.ID
ORDER BY cmt.ID DESC
FOR XML PATH ('')