Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need to do this one time table setup (if you don't want to use a Numbers Table, see alternative solution below):</p> <pre><code>SELECT TOP 10000 IDENTITY(int,1,1) AS Number INTO Numbers FROM sys.columns s1 CROSS JOIN sys.columns s2 ALTER TABLE Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number) </code></pre> <p>Once the Numbers table is set up, use this query:</p> <pre><code>DECLARE @ParentTable table (ID int,Name varchar(20)) DECLARE @ChildTable table (ID int,ParentID int,Name varchar(20)) INSERT INTO @ParentTable VALUES (1,'Bob') INSERT INTO @ChildTable VALUES (1,1,'Jim') INSERT INTO @ChildTable VALUES (2,1,'Ned') SELECT DISTINCT dt.Name,c.Name FROM (SELECT CASE WHEN n.Number=1 THEN NULL ELSE p.ID END AS ID,p.Name FROM @ParentTable p INNER JOIN Numbers n ON 1=1 WHERE p.ID=1 AND n.Number&lt;=2 ) dt LEFT OUTER JOIN @ChildTable c ON dt.ID=c.ParentID ORDER BY 1,2 </code></pre> <p>OUTPUT:</p> <pre><code>Name Name -------------------- -------------------- Bob NULL Bob Jim Bob Ned (3 row(s) affected) </code></pre> <p><strong>alternative solution</strong> if you don't want to create a Numbers table you can use this method, returns the same output as above:</p> <pre><code>SELECT DISTINCT dt.Name,c.Name FROM (SELECT CASE WHEN n.Number=1 THEN NULL ELSE p.ID END AS ID,p.Name FROM @ParentTable p INNER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY object_id) AS Number FROM sys.columns) n ON n.Number&lt;=2 WHERE p.ID=1 AND n.Number&lt;=2 ) dt LEFT OUTER JOIN @ChildTable c ON dt.ID=c.ParentID ORDER BY 1,2 </code></pre> <p>I was trying to use A CTE to expand the parent row, but it is hard without using a UNION!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload