{"id":3532,"date":"2012-04-24T03:29:27","date_gmt":"2012-04-24T03:29:27","guid":{"rendered":"https:\/\/test.simple-talk.com\/uncategorized\/hierarchical-queries-with-common-table-expressions\/"},"modified":"2016-07-28T10:50:46","modified_gmt":"2016-07-28T10:50:46","slug":"hierarchical-queries-with-common-table-expressions","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/blogs\/hierarchical-queries-with-common-table-expressions\/","title":{"rendered":"Hierarchical Queries with Common Table Expressions"},"content":{"rendered":"<p>I wanted a simple example of a hierarchical query using a common table expression in SQL Server.&#160; MSDN had an example called <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms186243.aspx\">Recursive Queries Using Common Table Expressions<\/a>, but it relied on the Adventure Works database and was joining across three different tables.&#160; Then I stumbled upon another blog called <a href=\"http:\/\/vyaskn.tripod.com\/hierarchies_in_sql_server_databases.htm\">Working with hierarchical data in SQL Server databases<\/a> that had all of the queries to make the tables and populate the data, but it was using stored procedures.&#160; So I took the liberty of putting them together into a very simple example that you can run:<\/p>\n<p>IF&#160; NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Emp]&#8217;) AND type in (N&#8217;U&#8217;))   <br \/>BEGIN    <br \/>&#160;&#160;&#160; &#8212; Create the table    <br \/>&#160;&#160;&#160; CREATE TABLE dbo.Emp    <br \/>&#160;&#160;&#160; (    <br \/>&#160;&#160;&#160;&#160;&#160;&#160;&#160; EmpID&#160;&#160;&#160;&#160;&#160;&#160;&#160; int&#160;&#160;&#160; PRIMARY KEY,    <br \/>&#160;&#160;&#160;&#160;&#160;&#160;&#160; EmpName&#160;&#160;&#160;&#160;&#160;&#160;&#160; varchar(30),    <br \/>&#160;&#160;&#160;&#160;&#160;&#160;&#160; MgrID&#160;&#160;&#160;&#160;&#160;&#160;&#160; int&#160;&#160;&#160; FOREIGN KEY REFERENCES Emp(EmpID)    <br \/>&#160;&#160;&#160; )    <br \/>&#160;&#160;&#160; <br \/>&#160;&#160;&#160; &#8212; Create a non-clustered index for query performance    <br \/>&#160;&#160;&#160; CREATE NONCLUSTERED INDEX NC_NU_Emp_MgrID ON dbo.Emp(MgrID)    <br \/>&#160;&#160;&#160; <br \/>&#160;&#160;&#160; &#8212; Populate the table with data    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 1, &#8216;President&#8217;, NULL    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 2, &#8216;Vice President&#8217;, 1    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 3, &#8216;CEO&#8217;, 2    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 4, &#8216;CTO&#8217;, 2    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 5, &#8216;Group Project Manager&#8217;, 4    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 6, &#8216;Project Manager 1&#8217;, 5    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 7, &#8216;Project Manager 2&#8217;, 5    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 8, &#8216;Team Leader 1&#8217;, 6    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 9, &#8216;Software Engineer 1&#8217;, 8    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 10, &#8216;Software Engineer 2&#8217;, 8    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 11, &#8216;Test Lead 1&#8217;, 6    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 12, &#8216;Tester 1&#8217;, 11    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 13, &#8216;Tester 2&#8217;, 11    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 14, &#8216;Team Leader 2&#8217;, 7    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 15, &#8216;Software Engineer 3&#8217;, 14    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 16, &#8216;Software Engineer 4&#8217;, 14    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 17, &#8216;Test Lead 2&#8217;, 7    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 18, &#8216;Tester 3&#8217;, 17    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 19, &#8216;Tester 4&#8217;, 17    <br \/>&#160;&#160;&#160; INSERT dbo.Emp SELECT 20, &#8216;Tester 5&#8217;, 17    <br \/>END    <br \/>GO&#160;&#160;&#160; <\/p>\n<p>&#8211;Hierarchical Query using Common Table Expressions   <br \/>WITH ReportingTree (EmpID, EmpName, MgrID, Lvl)    <br \/>AS    <br \/>(    <br \/>&#160;&#160;&#160; &#8211;Anchor Member    <br \/>&#160;&#160;&#160; SELECT *, 0 as Lvl FROM emp WHERE MgrId IS NULL    <br \/>&#160;&#160;&#160; UNION ALL    <br \/>&#160;&#160;&#160; &#8211;Recusive Member    <br \/>&#160;&#160;&#160; SELECT emp.EmpID, emp.EmpName, emp.MgrId, ReportingTree.Lvl+1     <br \/>&#160;&#160;&#160; FROM emp INNER JOIN ReportingTree     <br \/>&#160;&#160;&#160;&#160;&#160;&#160;&#160; on emp.MgrID = ReportingTree.EmpID    <br \/>)    <br \/>SELECT * FROM ReportingTree<\/p>\n<p>You will, however, need to refer to the MSDN documentation link to see how it&#8217;s working.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I wanted a simple example of a hierarchical query using a common table expression in SQL Server.&#160; MSDN had an example called Recursive Queries Using Common Table Expressions, but it relied on the Adventure Works database and was joining across three different tables.&#160; Then I stumbled upon another blog called Working with hierarchical data in&#8230;&hellip;<\/p>\n","protected":false},"author":46738,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[],"coauthors":[],"class_list":["post-3532","post","type-post","status-publish","format-standard","hentry","category-blogs"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/3532","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/46738"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=3532"}],"version-history":[{"count":2,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/3532\/revisions"}],"predecessor-version":[{"id":42150,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/3532\/revisions\/42150"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=3532"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=3532"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=3532"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=3532"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}