With T-SQL, is it possible to write a query that returns results that look like this?
Parent A ChildOfParentA_1 ChildField1 ChildField2 ChildOfParentA_2 ChildField1 ChildField2 ChildOfParentA_3 ChildField1 ChildField2 Parent B ChildOfParentB_1 ChildField1 ChildField2 ChildOfParentB_2 ChildField1 ChildField2 ChildOfParentB_3 ChildField1 ChildField2
In these results, there is a row that contains only one field for each parent record, with extra fields being set to NULL. Then, beneath parent record, there is a row for child records, which has three fields.
I know how to accomplish this using temporary tables and cursors, but I’d really like to have a single query that would return this information, in this format, if it’s even possible.
I’m assuming your parent and child records are in different tables, and can be joined by a ParentID that resides on both tables. The following query selects records from both tables, formats them such that they have the same number of columns, unions them together, and outputs them with a little formatting.
Standard disclaimer: SQL is not really designed for formatting output, so if you can shift the responsibility for the tabbing/indentation to the presentation layer, that’s usually better. But if you must do it in SQL (and sometimes we must!) this approach should do the trick. 🙂
Good luck!