Chapter 4. Hierarchies in SQL
Hierarchical structures have a sort of nondeterministic nature in
that the exact structure is determined only when you populate
the hierarchy
with data. This makes them appealing for various sorts of
applications. An employment hierarchy is a classical example of such
a structure. A company will have employees. Supervisors will be
assigned to lead groups of employees. Those supervisors, in turn,
will report to managers. Low-level managers will report to
higher-level managers. Eventually, you get to the top where you often
find a chief executive officer (CEO). If you sketch it out, the
typical company organization chart will look like an upside down
tree, with some branches in the tree being wider and narrower than
others. Hierarchical structures are widely used in procedural
languages, such as C, but are rather underutilized in SQL, because
they conflict with the inherent table-shaped data layout of
relational databases.
Almost any type of complex application can make use of a hierarchical
model to some degree or another. The recipes in this chapter show you
how to manipulate hierarchical data using Transact-SQL. This chapter
will discuss three major topics:
Specialized hierarchies
General hierarchies
Efficiency extensions
Some vendors, Oracle Corporation being among the most notable, have
extended their SQL syntax with additional functionality to support
querying hierarchical data. Unfortunately, neither Sybase nor
Microsoft have chosen to implement such extensions in Transact-SQL.
Although the Transact-SQL language hasn't been
designed to support dynamic structures such as trees, programmers
have come up with some reasonably efficient design patterns that
address the common operations that you need to perform on
hierarchical data. As an added bonus, the lack of vendor-specific
functionality tends to make these solutions more easily portable
across database platforms.
|