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

0

Please login or register to vote for this query.

(click on this box to dismiss)

Stack Overflow

Q&A for professional and enthusiast programmers

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');

INSERT INTO @Comments
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 * FROM @Comments;

SELECT '[ ' + STUFF(Z.Messages, 1, 2, '') + ' ] ' AS JSON
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 + '" }'
    FROM @Comments cmt
    WHERE MessageID = msg.ID
    ORDER BY cmt.ID DESC
    FOR XML PATH ('')
    ) AS X (Comments)
ORDER BY msg.ID DESC
) AS Y (MessageWComments)
FOR XML PATH ('')) AS Z(Messages)

Enter Parameters

Options:
Switch sites:
loading Hold tight while we fetch your results