Using SQL Server 2008 and any available features of TSQL, I am trying to work out how to if a set-based solution that does not involve a temp table exists for the following problem:
Given a set of nodes that have a parent-child relationship, and a set of key-value pairs that apply to each, and given that the value (for a given key-value pair) at a deeper level of the node hierarchy will override a value with the same key that is inherited from an ancestor node, select:
- the full set of key-value pairs that apply to a given node
- the set of inherited values for that node
The schema is as follows:
create table Node
(
ID bigint identity primary key,
ParentID bigint null foreign key references Node(ID),
Name nvarchar(100)
);
create table KeyValuePair
(
ID bigint identity primary key,
KeyName nvarchar(100) not null,
Value nvarchar(1000) not null,
NodeID bigint not null foreign key references Node(ID),
unique (KeyName, NodeID)
);
The result set would essentially include the columns KeyName
, Value
, InheritedValue
.
I've been trying to do this using a common table expression but the logic of it is a bit tricky.