{"id":801,"date":"2014-05-06T09:46:13","date_gmt":"2014-05-06T13:46:13","guid":{"rendered":"http:\/\/binaryworld.net\/blogs\/?p=801"},"modified":"2015-12-01T16:37:36","modified_gmt":"2015-12-01T21:37:36","slug":"sql-parent-child-query-example-recursive-cte-hierarchy","status":"publish","type":"post","link":"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/","title":{"rendered":"SQL Server parent child query example using recursive CTE (Common Table Expression)"},"content":{"rendered":"<p>Many times we have to write <strong><em>recursive parent child\u00a0query <\/em><\/strong>(Multiple levels of Parent-Child Links)\u00a0 in SQL Server. There are multiple approaches to achieve this<\/p>\n<ol>\n<li>Using <strong>Hierarchy ID builtin CLR datatype<\/strong> in SQL Server 2008 or higher (not ion sql server 2000, 2005)<\/li>\n<li>Using <strong>CTE (Common Table Expression)<\/strong> (sql server 2005 or higher)<\/li>\n<li>Custom recursive function or stored proc.<\/li>\n<\/ol>\n<p>I think Most effective way <strong>parent child query<\/strong> to get unknown levels of hierarchy is using&#8230;. <strong>Common Table Expression (CTE)<\/strong> feature of SQL Server (introduced in SQL Server 2005).<\/p>\n<p>Common examples of multiple levels of nested <em>parent child query<\/em> are &#8230; getting\u00a0parent branches of\u00a0selected employee, navigate through org chart <em>hierarchy using sql<\/em>, navigate through <em>product hierarchy<\/em> using t-sql<\/p>\n<p>Below is complete T-SQL example on how to write\u00a0<em>parent child query<\/em> using CTE (2 examples&#8230; Find all Children of selected Parent node, Find all Parent Nodes or Selected Child Node)<\/p>\n<p>Basic syntax of SQL CTE like below<\/p>\n<p>WITH <em>Recursive-CTE-Query<\/em> AS (<br \/>\u00a0 {Anchor Query}<br \/>\u00a0 UNION ALL<br \/>\u00a0 {Query joined to <em>Recursive-CTE-Query<\/em>}<br \/>)<br \/>SELECT * FROM <em>Recursive-CTE-Query<\/em><\/p>\n<p>Here is full example of SQL Server CTE to get hirarchy of parent child nodes stored in a table.<\/p>\n<h3>Example of recursive parent child query in SQL Server using CTE (Common Table Expression)<\/h3>\n<pre class=\"brush: sql; gutter: true\">create table #ParentChildTable \r\n(nodeID int not null ,parentNodeID int null ,ClassType varchar(100) not null\r\n)\r\ngo\r\n\r\ninsert into #ParentChildTable values(1,null,&#039;Vehicle&#039;)\r\ninsert into #ParentChildTable values(2,1,&#039;GroundVehicle&#039;)\r\ninsert into #ParentChildTable values(3,1,&#039;AirVehicle&#039;)\r\ninsert into #ParentChildTable values(4,2,&#039;Car&#039;)\r\ninsert into #ParentChildTable values(5,2,&#039;Truck&#039;)\r\ninsert into #ParentChildTable values(6,2,&#039;FlyingCar&#039;)\r\ninsert into #ParentChildTable values(7,4,&#039;SUV&#039;)\r\ninsert into #ParentChildTable values(8,4,&#039;VAN&#039;)\r\ninsert into #ParentChildTable values(9,8,&#039;FordWindStar&#039;)\r\ninsert into #ParentChildTable values(10,3,&#039;Airplane&#039;)\r\ninsert into #ParentChildTable values(11,4,&#039;BMW-325&#039;)\r\n\r\n go\r\n\r\n --\/\/Find all parent nodes of specified Child Node(s)\r\n;WITH Heirarchy --\/\/Create CTE which can be called recursively\r\nAS\r\n(\r\n   SELECT Path=cast(T1.ClassType + &#039;-&#039; as varchar(1000)), Level=1, T1.NodeID,T1.ParentNodeID,T1.ClassType FROM #ParentChildTable T1\r\n   WHERE T1.NodeID=9 -- or -- T1.NodeID IN (9,10) --\/\/&lt;&lt; pass child node ID HERE\r\n   UNION ALL\r\n   SELECT Path1=cast(TH.Path + T1.ClassType + &#039;-&#039; as varchar(1000)),Level=TH.Level+1, T1.NodeID,T1.ParentNodeID,T1.ClassType\r\n   FROM #ParentChildTable T1 INNER JOIN Heirarchy TH ON TH.parentNodeID = T1.NodeID --&lt;&lt; Child to Parent \r\n)\r\nselect * from Heirarchy\r\n\r\n --\/\/Find all child nodes of Specified parent Node\r\n;WITH Heirarchy --\/\/Create CTE which can be called recursively\r\nAS\r\n(\r\n   SELECT Path=cast(T1.ClassType + &#039;-&#039; as varchar(1000)), Level=1, T1.NodeID,T1.ParentNodeID,T1.ClassType FROM #ParentChildTable T1\r\n   WHERE T1.NodeID=1 -- or -- T1.NodeID IN (9,10) --\/\/&lt;&lt; pass parent node ID HERE\r\n   UNION ALL\r\n   SELECT Path=cast(TH.Path + T1.ClassType + &#039;-&#039; as varchar(1000)),Level=TH.Level+1, T1.NodeID,T1.ParentNodeID,T1.ClassType\r\n   FROM #ParentChildTable T1 INNER JOIN Heirarchy TH ON TH.NodeID = T1.ParentNodeID --&lt;&lt; Parent to Child\r\n)\r\nselect * from Heirarchy \r\n\r\ngo\r\ndrop table #ParentChildTable \r\ngo\r\n\r\nHere is the output when you run these two queries<\/pre>\n<figure id=\"attachment_817\" aria-describedby=\"caption-attachment-817\" style=\"width: 612px\" class=\"wp-caption alignnone\"><a href=\"http:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-817\" alt=\"How to get parent child relationship using recursive CTE query \" src=\"http:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy.jpg\" width=\"612\" height=\"306\" srcset=\"https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy.jpg 612w, https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy-300x150.jpg 300w, https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy-100x50.jpg 100w, https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy-150x75.jpg 150w, https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy-200x100.jpg 200w, https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy-450x225.jpg 450w, https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy-600x300.jpg 600w\" sizes=\"(max-width: 612px) 100vw, 612px\" \/><\/a><figcaption id=\"caption-attachment-817\" class=\"wp-caption-text\">How to get parent child relationship using recursive CTE query<\/figcaption><\/figure>\n<p>&nbsp;<\/p>\n<p>\u00a0<a title=\"SQL Server CTE  (recursive parent child query)\" href=\"http:\/\/technet.microsoft.com\/en-us\/library\/ms190766(v=SQL.105).aspx\" target=\"_blank\">Click here<\/a> to learn more about CTE on MSDN<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Many times we have to write recursive parent child\u00a0query (Multiple levels of Parent-Child Links)\u00a0 in SQL Server. There are multiple approaches to achieve this Using Hierarchy ID builtin CLR datatype in SQL Server 2008 or higher (not ion sql server &hellip;<\/p>\n<p class=\"read-more\"> <a class=\"more-link\" href=\"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/\"> <span class=\"screen-reader-text\">SQL Server parent child query example using recursive CTE (Common Table Expression)<\/span> Read More &raquo;<\/a><\/p>\n","protected":false},"author":1,"featured_media":817,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27,35],"tags":[158,130],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v22.3 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\r\n<title>SQL Server parent child query example using recursive CTE (Common Table Expression) - BinaryWorld Blog<\/title>\r\n<meta name=\"description\" content=\"This article explains how to write a simple and efficient parent child query using CTE (sql server recursive query technique)\" \/>\r\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/\" \/>\r\n<meta property=\"og:locale\" content=\"en_US\" \/>\r\n<meta property=\"og:type\" content=\"article\" \/>\r\n<meta property=\"og:title\" content=\"SQL Server parent child query example using recursive CTE (Common Table Expression) - BinaryWorld Blog\" \/>\r\n<meta property=\"og:description\" content=\"This article explains how to write a simple and efficient parent child query using CTE (sql server recursive query technique)\" \/>\r\n<meta property=\"og:url\" content=\"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/\" \/>\r\n<meta property=\"og:site_name\" content=\"BinaryWorld Blog\" \/>\r\n<meta property=\"article:published_time\" content=\"2014-05-06T13:46:13+00:00\" \/>\r\n<meta property=\"article:modified_time\" content=\"2015-12-01T21:37:36+00:00\" \/>\r\n<meta property=\"og:image\" content=\"https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy.jpg\" \/>\r\n\t<meta property=\"og:image:width\" content=\"612\" \/>\r\n\t<meta property=\"og:image:height\" content=\"306\" \/>\r\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\r\n<meta name=\"author\" content=\"Binary World\" \/>\r\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\r\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Binary World\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\r\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/\",\"url\":\"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/\",\"name\":\"SQL Server parent child query example using recursive CTE (Common Table Expression) - BinaryWorld Blog\",\"isPartOf\":{\"@id\":\"https:\/\/binaryworld.net\/blogs\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy.jpg\",\"datePublished\":\"2014-05-06T13:46:13+00:00\",\"dateModified\":\"2015-12-01T21:37:36+00:00\",\"author\":{\"@id\":\"https:\/\/binaryworld.net\/blogs\/#\/schema\/person\/77cf0a9a512dd22bff93c6a1b6374fe0\"},\"description\":\"This article explains how to write a simple and efficient parent child query using CTE (sql server recursive query technique)\",\"breadcrumb\":{\"@id\":\"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/#primaryimage\",\"url\":\"https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy.jpg\",\"contentUrl\":\"https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy.jpg\",\"width\":612,\"height\":306,\"caption\":\"How to get parent child relationship using recursive CTE query\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/binaryworld.net\/blogs\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"SQL Server parent child query example using recursive CTE (Common Table Expression)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/binaryworld.net\/blogs\/#website\",\"url\":\"https:\/\/binaryworld.net\/blogs\/\",\"name\":\"BinaryWorld Blog\",\"description\":\"Tips and Tutorials for Microsoft SQL Server, SSIS, SSAS, Business Intelligence, C#, .net\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/binaryworld.net\/blogs\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/binaryworld.net\/blogs\/#\/schema\/person\/77cf0a9a512dd22bff93c6a1b6374fe0\",\"name\":\"Binary World\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/binaryworld.net\/blogs\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/eaea47799daa577835eb53e64dfd3e13?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/eaea47799daa577835eb53e64dfd3e13?s=96&d=mm&r=g\",\"caption\":\"Binary World\"},\"description\":\"Binary World is a Software Development company located in Atlanta, USA (since 2007). Binary World specialized in Business Intelligence, mobile, cloud computing and .Net Application Development.\",\"url\":\"https:\/\/binaryworld.net\/blogs\/author\/admin\/\"}]}<\/script>\r\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"SQL Server parent child query example using recursive CTE (Common Table Expression) - BinaryWorld Blog","description":"This article explains how to write a simple and efficient parent child query using CTE (sql server recursive query technique)","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/","og_locale":"en_US","og_type":"article","og_title":"SQL Server parent child query example using recursive CTE (Common Table Expression) - BinaryWorld Blog","og_description":"This article explains how to write a simple and efficient parent child query using CTE (sql server recursive query technique)","og_url":"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/","og_site_name":"BinaryWorld Blog","article_published_time":"2014-05-06T13:46:13+00:00","article_modified_time":"2015-12-01T21:37:36+00:00","og_image":[{"width":612,"height":306,"url":"https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy.jpg","type":"image\/jpeg"}],"author":"Binary World","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Binary World","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/","url":"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/","name":"SQL Server parent child query example using recursive CTE (Common Table Expression) - BinaryWorld Blog","isPartOf":{"@id":"https:\/\/binaryworld.net\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/#primaryimage"},"image":{"@id":"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/#primaryimage"},"thumbnailUrl":"https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy.jpg","datePublished":"2014-05-06T13:46:13+00:00","dateModified":"2015-12-01T21:37:36+00:00","author":{"@id":"https:\/\/binaryworld.net\/blogs\/#\/schema\/person\/77cf0a9a512dd22bff93c6a1b6374fe0"},"description":"This article explains how to write a simple and efficient parent child query using CTE (sql server recursive query technique)","breadcrumb":{"@id":"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/#primaryimage","url":"https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy.jpg","contentUrl":"https:\/\/binaryworld.net\/blogs\/wp-content\/uploads\/2014\/05\/parent-child-data-sql-server-cte-hirarchy.jpg","width":612,"height":306,"caption":"How to get parent child relationship using recursive CTE query"},{"@type":"BreadcrumbList","@id":"https:\/\/binaryworld.net\/blogs\/sql-parent-child-query-example-recursive-cte-hierarchy\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/binaryworld.net\/blogs\/"},{"@type":"ListItem","position":2,"name":"SQL Server parent child query example using recursive CTE (Common Table Expression)"}]},{"@type":"WebSite","@id":"https:\/\/binaryworld.net\/blogs\/#website","url":"https:\/\/binaryworld.net\/blogs\/","name":"BinaryWorld Blog","description":"Tips and Tutorials for Microsoft SQL Server, SSIS, SSAS, Business Intelligence, C#, .net","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/binaryworld.net\/blogs\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/binaryworld.net\/blogs\/#\/schema\/person\/77cf0a9a512dd22bff93c6a1b6374fe0","name":"Binary World","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/binaryworld.net\/blogs\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/eaea47799daa577835eb53e64dfd3e13?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/eaea47799daa577835eb53e64dfd3e13?s=96&d=mm&r=g","caption":"Binary World"},"description":"Binary World is a Software Development company located in Atlanta, USA (since 2007). Binary World specialized in Business Intelligence, mobile, cloud computing and .Net Application Development.","url":"https:\/\/binaryworld.net\/blogs\/author\/admin\/"}]}},"_links":{"self":[{"href":"https:\/\/binaryworld.net\/blogs\/wp-json\/wp\/v2\/posts\/801"}],"collection":[{"href":"https:\/\/binaryworld.net\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/binaryworld.net\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/binaryworld.net\/blogs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/binaryworld.net\/blogs\/wp-json\/wp\/v2\/comments?post=801"}],"version-history":[{"count":0,"href":"https:\/\/binaryworld.net\/blogs\/wp-json\/wp\/v2\/posts\/801\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/binaryworld.net\/blogs\/wp-json\/wp\/v2\/media\/817"}],"wp:attachment":[{"href":"https:\/\/binaryworld.net\/blogs\/wp-json\/wp\/v2\/media?parent=801"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/binaryworld.net\/blogs\/wp-json\/wp\/v2\/categories?post=801"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/binaryworld.net\/blogs\/wp-json\/wp\/v2\/tags?post=801"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}