select versionid, folder, parent, grandparent, T1.formatid, Format, type, HowMany, 
[SectionFormatName],[IsStepSection]
--,TopMargin,PageLength,FooterLength,LeftMargin,PageWidth 
from 
(select vv.versionid, ff.name folder, pf.name parent, gf.name grandparent, vv.formatid, fm.name Format, cc.type, 
cc.type - 10000 Ind, count(*) HowMany
from vefn_GetVersionFormatItems('') vv
Join contents cc on cc.ContentID = vv.contentID
join docversions dv on vv.versionid = dv.versionid
Join folders ff on ff.FolderID = DV.FolderID
Join folders pf on pf.FolderID = ff.parentID
Join folders gf on gf.FolderID = pf.parentid
join formats fm on fm.formatid = vv.formatid
where cc.type between 10000 and 19999
group by vv.versionid, ff.name, pf.name, gf.name, vv.formatid, fm.name, cc.type) T1
Join (select FormatID, v.query('..') DocStyle
,10000 + v.value('../@Index', 'int') [SectionType]
,[Name] [FormatName]
,v.value('../@Name', 'varchar(255)') [SectionFormatName]
,v.value('../@IsStepSection', 'varchar(255)') [IsStepSection]
--,v.value('@TopMargin', 'real') TopMargin
--,v.value('@PageLength', 'real') PageLength
--,v.value('@FooterLength', 'real') FooterLength
--,v.value('@LeftMargin', 'real') LeftMargin
--,v.value('@PageWidth', 'real') PageWidth
from Formats
Cross APPLY Data.nodes('//DocStyle/Layout') TempXML(v)
where FormatID In (select distinct formatid from vefn_GetVersionFormatItems(''))) 
FF on FF.FormatID = T1.FormatID and ff.SectionType = T1.Type
--Where IsStepSection = 'FALSE' and PageLength < PageWidth
Order by sectionformatname
