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)

Internet of Things Meta

Q&A about the site for builders and users of networked sensors and control devices in the contexts of smart homes, industry automation, or environmental sensors

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 @Comments;

Enter Parameters

Options:
Switch to main site
loading Hold tight while we fetch your results