This is called a Pivot. To have a dynamic number of columns, you will probably have to use dynamic SQL- creating a query on the fly from another query, and using whatever eval method is available. Depending on what language you are using, this may be easily handled by the calling code. I would recommend refactoring to do it another way, or get ready for a few hours of learning. I can't really help you with the query without more info- the db schema, and what sql db you're using.
Here's a fairly complicated example, although I'm not sure how helpful it would be.
ALTER PROCEDURE [dbo].[CMS_GetCollection]
@sectionContentTemplateID int
,@count int = null
AS
BEGIN
SET NOCOUNT ON;
SET NOCOUNT ON;
declare @columns varchar(max)
select
@columns = COALESCE(@columns + ',[' + cte.name + '/' + a.name + ']', '[' + cte.name + '/' + a.name + ']')
from tcmssection_contenttemplate sct
inner join tcmssection s on s.sectionid = sct.sectionid
inner join tcmscontenttemplate ct on ct.contenttemplateid = sct.contenttemplateid
inner join tcmscontenttemplate_element cte on cte.contenttemplateid = ct.contenttemplateid
inner join tcmselement e on cte.elementid = e.elementid
inner join tcmsattribute a on e.elementid = a.elementid
where
a.isadmin = 0
and sct.sectioncontenttemplateid = @sectionContentTemplateID
declare @query varchar(max)
set @query =
'select ' + case when @count is not null then
' top ' + convert(varchar(10),@count) else '' end + '
[url]
,pageId,pageName,sortOrder
,[date]
, ' + @columns + '
from (
select
s.domainpath + p.filename as [url]
,cte.name + ''/'' + a.name as [element.attribute]
,isnull(pva.valuevarchar, isnull(pva.valuetext,'''')) as [value]
,pv.datepublished as [date],isnull(p.sortOrder,0) as sortOrder,p.pageID,p.name as pageName
from tcmssection_contenttemplate sct
inner join tcmssection s on s.sectionid = sct.sectionid
inner join tcmspage p on p.sectioncontenttemplateid = sct.sectioncontenttemplateid
inner join tcmscontenttemplate ct on ct.contenttemplateid = sct.contenttemplateid
inner join tcmscontenttemplate_element cte on cte.contenttemplateid = ct.contenttemplateid
inner join tcmselement e on cte.elementid = e.elementid
inner join tCMSPageVersion pv on p.pageID = pv.pageID
and pv.pageVersionID = (
select top 1 pageVersionID
from tCMSPageVersion
where pageID = p.pageID and datePublished is not null and datecancelled is null
order by datePublished desc
)
inner join tcmsattribute a on e.elementid = a.elementid
left outer join tcmspageversion_element pve on pve.pageversionid = pv.pageversionid
and pve.elementid = e.elementid and pve.name = cte.name
left outer join tcmspageversion_attribute pva on pva.attributeid = a.attributeid
and pve.pageversionelementid = pva.pageversionelementid
where
p.isDeleted = 0
and a.isadmin = 0
and sct.sectioncontenttemplateid = ' + convert(varchar(10), @sectionContentTemplateID) + '
) [data]
pivot (
max([value])
for [element.attribute]
in ( ' + @columns + ' )
) as [pivot]
order by [date] desc'
execute(@query)
END