sql server 2008 - T-SQL - Best way to select rows that corresponds to a category and default category if the category is not configured -


i have table of configuration data can associated recipe (category more generic).

like this:

recipes:

id name 1 default 2 3 b 

configuration data

id equipment parentid recipeid 1  3420      1         1  2  3420      1         2 3  3421      1         1 4  3421      1         2 5  3422      1         1 

i want know how select configuration data recipe "a", , fall on "default" values if recipe not configured configuration data row. this:

id equipment parentid recipeid 2  3420      1         2 4  3421      1         2 5  3422      1         1 

i found unsure approach:

select * configurationdata recipeid=2 , parentid=1 union  select * configurationdata recipeid=1 , parentid=1 , equipment not in (select equipment configurationdata  recipeid=2 , parentid=1) 

something using cte?

/**   * first declare id search  */ declare @recipeid int   set @recipeid = 2 -- change recipe want select  /**  * actual query  */ cte (   select r.id recipe, c.id, c.equipment, c.recipeid, row_number() on (partition r.id, c.equipment order c.recipeid desc) row          recipes r inner join configuration c on r.id = c.recipeid or c.recipeid = 1 ) select    id, equipment, recipeid    cte     row = 1     , r.id = @recipeid 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -