sql - How to write a query for a nested object that varies on a field of the parent? -
this may difficult question ask correctly. idea have thing has schema result in json object so:
{ id:1, x:1, y:1, type:"map" settings: {... settings type "map" ...}}
each of fields id, x, y, type
directly column in table. want take string of type
"map", , in map_settings table properties in properties.
i have instance:
{ id:1, x:1, y:1, type:"graph" settings: {... settings type "map" ...}}
which has different type
. , reference graph_settings table instead.
how can write query that?
i'm not sure how sql server produce json, produce similar in xml. perhaps there way convert xml json..
i'm assuming schema this:
create table [thing] ( [id] int, [x] int, [y] int, [type] varchar(10) ) create table [map_settings] ( [thing_id] int, [mapsetting1] int, [mapsetting2] int ) create table [graph_settings] ( [thing_id] int, [graphsetting3] int, [graphsetting4] int )
some data:
insert [thing] values (1, 1, 1, 'map'), (2, 1, 1, 'graph') insert [map_settings] values (1, 0, 0) insert [graph_settings] values (2, 0, 0)
and query produces xml:
select thing.id [@id], thing.[x] [@x], thing.[y] [@y], thing.[type] [@type], case thing.[type] when 'map' ( select [mapsetting1] [@mapsetting1], [mapsetting2] [@mapsetting2] [map_settings] ms ms.[thing_id] = thing.[id] xml path ('settings'), type ) when 'graph' ( select [graphsetting3] [@graphsetting3], [graphsetting4] [@graphsetting4] [graph_settings] gs gs.[thing_id] = thing.[id] xml path ('settings'), type ) end [thing] thing xml path ('thing')
the output:
<thing id="1" x="1" y="1" type="map"> <settings mapsetting1="0" mapsetting2="0" /> </thing> <thing id="2" x="1" y="1" type="graph"> <settings graphsetting3="0" graphsetting4="0" /> </thing>
does help?
Comments
Post a Comment