I wanted to add my βown answerβ really just for completeness, to possibly help others. However, this is definitely based on the great help from @Mikael above! so again, this is really for completeness - all this is attached by @Mikael.
I basically ended up with the following proc. I needed to select some data / filter and get some combined data and enable some Boolean filtering on some input parameters. Then go to the next section, which created a temporary table of my relational data, and the required xml nodes through the cross are applied. The final step was to then collapse the results / dynamically create columns from the selected XML node ..
CREATE PROCEDURE [dbo].[usp_RPT_ExtractFlattenentries] @CompanyID int, @MainSelector nvarchar(50) = null, @SecondarySelector nvarchar(255) = null, @DateFrom datetime = '01-jan-2012', @DateTo datetime = '31-dec-2100', @SysReference nvarchar(20) = null AS BEGIN SET NOCOUNT ON; -- Create the table var to hold the XML form data from the entries declare @FeedbackXml table ( ID int identity primary key, XMLCol xml, CompanyName nvarchar(20), SysReference nvarchar(20), RecordDate datetime, EntryName nvarchar(255), MainSelector nvarchar(50) ) -- STEP 1: Get the raw submission data based on the params passed in -- *Note: The double casting is necessary as the "form" field is nvarchar (not varchar) and we need xml in UTF-8 format begin insert into @FeedbackXml (XMLCol, CompanyName, SysReference, RecordDate, EntryName, MainSelector) select cast(cast(e.form as nvarchar(max)) as xml), c.name, e.SysReference, e.RecordDate, e.name, e.wizard from entries s left join companies o on e.companies = c.ID where (@CompanyID = -1 or @CompanyID = e.companies) and (@MainSelector is null or @MainSelector = e.wizard) and (@SecondarySelector is null or @SecondarySelector = e.name) and (@SysReference is null or @SysReference = e.SysReference) and (e.RecordDate >= @DateFrom and e.RecordDate <= @DateTo) end -- STEP 2: Flatten the required XML structure to provide a base for the pivot, and include other fields we wish to output select dense_rank() over(order by ID) as ID, T.RecordDate, T.CompanyName, T.SysReference, T.EntryName, T.MainSelector, FNvalue('(FieldNameNode/text())[1]', 'nvarchar(max)') as FieldName, FNvalue('(FieldNameValue/text())[1]', 'nvarchar(max)') as FieldValue into
Again, in fact, only added this answer to present the full picture from my point of view, and may help others.