Note that there are some explanatory texts on larger screens.

plurals
  1. POFiltering a bottom up recursive CTE with Sql Server 2005
    primarykey
    data
    text
    <p>I'm trying to query a hierarchy of data in a single database table from the bottom up (I don't want to include parents that don't have a particular type of child due to authorities). The schema and sample data are as follows:</p> <pre><code>create table Users( id int, name varchar(100)); insert into Users values (1, 'Jill'); create table nodes( id int, name varchar(100), parent int, nodetype int); insert into nodes values (1, 'A', 0, 1); insert into nodes values (2, 'B', 0, 1); insert into nodes values (3, 'C', 1, 1); insert into nodes values (4, 'D', 3, 2); insert into nodes values (5, 'E', 1, 1); insert into nodes values (6, 'F', 5, 2); insert into nodes values (7, 'G', 5, 2); create table nodeAccess( userid int, nodeid int, access int); insert into nodeAccess values (1, 1, 1); insert into nodeAccess values (1, 2, 1); insert into nodeAccess values (1, 3, 1); insert into nodeAccess values (1, 4, 1); insert into nodeAccess values (1, 5, 1); insert into nodeAccess values (1, 6, 0); insert into nodeAccess values (1, 7, 1); with Tree(id, name, nodetype, parent) as ( select n.id, n.name, n.nodetype, n.parent from nodes as n inner join nodeAccess as na on na.nodeid = n.id where na.access =1 and na.userid=1 and n.nodetype=2 union all select n.id, n.name, n.nodetype, n.parent from nodes as n inner join Tree as t on t.parent = n.id inner join nodeAccess as na on na.nodeid = n.id where na.access =1 and na.userid=1 and n.nodetype=1 ) select * from Tree </code></pre> <p>Yields:</p> <pre><code> id name nodetype parent 4 D 2 3 7 G 2 5 5 E 1 1 1 A 1 0 3 C 1 1 1 A 1 0 </code></pre> <p>How can I not include the duplicates in the result set? The queries against the real tables have many more nodes at the lowest levels and hence many more duplicates of the parent nodes. The solution needs to work with at least SQL Server 2005.</p> <p>Thanks in advance!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload