Select from XML with unknown structure

qwerta369

New Member
I have a table in SQL Server 2008 with the following structure:\[code\]id = intnumero = intdatos = xml[other_misc_fields]\[/code\]You can see the table with some example data on this sql fiddle. As you can see on the link, the field datos (data) is an XML. This XML doesn't have a known structure. All I know is that the root is "lote" and that every field has an attribute "title" which is the "display name" of the field. I would like to be able to query something along this line\[code\]id | numero | display_name_field_1 | display_name_field_2 | display_name_field_3 1 | 23 | value_field_1 | value_field_2 | value_field_3\[/code\]Using some dynamic sql (from another so answer) I'm able to get the value from each node, but I can't figure out how to rename it using the title attribute:\[code\]select @SQL = 'select '+stuff( ( select ',T.N.value('''+T.N.value('local-name(.)', 'sysname')+'[1]'', ''varchar(max)'') as '+T.N.value('local-name(.)', 'sysname') from @XML.nodes('/*[local-name(.)=sql:variable("@KnownName")]/*') as T(N) for xml path(''), type ).value('.', 'nvarchar(max)'), 1, 1, '')+ ' from @XML.nodes(''/*[local-name(.)=sql:variable("@KnownName")]'') as T(N)\[/code\]Where @KnownName is "lote". How can I modify that query so the field renames to the @title attribute of the node? Or, alternatively, is there a better way to do this than dynamic sql?
 
Back
Top