{"id":18294,"date":"2022-06-10T07:02:00","date_gmt":"2022-06-10T05:02:00","guid":{"rendered":"https:\/\/expert-only.com\/?p=18294"},"modified":"2023-03-10T09:51:33","modified_gmt":"2023-03-10T08:51:33","slug":"call-a-sql-server-cte-multiple-times","status":"publish","type":"post","link":"https:\/\/expert-only.com\/en\/t-sql\/call-a-sql-server-cte-multiple-times\/","title":{"rendered":"Call a SQL Server CTE multiple times and reuse the data"},"content":{"rendered":"\n<h4 class=\"has-text-align-center wp-block-heading\" id=\"h-how-to-run-multiple-select-queries-on-the-same-sql-server-cte\"><strong><em>How to run multiple SELECT queries on the same SQL Server CTE?<\/em><\/strong><\/h4>\n\n\n\n<p>Is it possible to execute several selection queries on a CTE, i.e. to call a SQL Server CTE multiple times in the same stored procedure for example? First of all, a CTE (Common Table Expression) allows you to reuse the result of a selection query. It is a temporary dataset, available only during the script. The CTE is widely used in particular to create recursive queries.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Can a SQL Server CTE be called multiple times?<\/h2>\n\n\n\n<p>It is true that on the second SELECT query on a CTE this error is returned by SQL Server:<\/p>\n\n\n\n<p><em>(1 row(s) affected)<br>Msg 208, Level 16, State 1, Line 9<br>Invalid object name &#8216;MyCTE&#8217;.<\/em><\/p>\n\n\n\n<p>Indeed, it seems impossible to reuse a CTE several times. Otherwise, the error is displayed, Invalid object name with a SQL Server CTE. So, no CTE&#8217;s are not made to be called multiple times. The first SELECT query on the CTE works but not the following ones. Here is an example of a CTE with SELECT queries:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"mssql\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">WITH MyCTE ([Yesterday], [Today], [Tomorrow]) AS\n(\n  SELECT \n    getdate()-1  as [Yesterday], \n    getdate()    as [Today], \n    getdate()+1  as [Tomorrow]\n)\n\nSELECT [Yesterday] FROM MyCTE;\n\nSELECT [Today]     FROM MyCTE;\n\nSELECT [Tomorrow]  FROM MyCTE;\n<\/pre>\n\n\n\n<p>In SQL Server, a <a href=\"https:\/\/learn.microsoft.com\/en-us\/sql\/t-sql\/queries\/with-common-table-expression-transact-sql?view=sql-server-ver15\" target=\"_blank\" rel=\"noreferrer noopener\">CTE<\/a> for Common Table Expression is a temporary object that exists only after it is created. It is then deleted after the first query executed on it. Therefore, a temporary table must be used to preserve the results.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using a temporary table instead of the CTE<\/h2>\n\n\n\n<p>This query which replaces the ETC with a temporary table works perfectly.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"mssql\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">IF OBJECT_ID('tempdb..#Temp_Table') IS NOT NULL\n   DROP TABLE #Temp_Table;\n\nSELECT \n  getdate()-1  as [Yesterday], \n  getdate()    as [Today], \n  getdate()+1  as [Tomorrow]\nINTO      #Temp_Table;\n\nSELECT [Yesterday] FROM #Temp_Table;\nSELECT [Today]     FROM #Temp_Table;\nSELECT [Tomorrow]  FROM #Temp_Table;\n<\/pre>\n\n\n\n<p>Also, be sure to <a href=\"https:\/\/expert-only.com\/en\/t-sql\/check-if-table-exists-in-sql-server\/\">check if the table exists and delete it first to avoid errors<\/a>. Finally, here is a tutorial on another SQL Server topic, to learn how to transform rows into columns from a SQL Server table. You need to <a href=\"https:\/\/expert-only.com\/en\/t-sql\/sql-server-pivot-query-example\/\">use the SQL Server PIVOT query<\/a>.<\/p>\n\n\n\n<p>Finally, this tutorial explains a method to call a SQL Server CTE multiple times and get around the problem.<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-sql-and-it-tutorials wp-block-embed-sql-and-it-tutorials\"><div class=\"wp-block-embed__wrapper\">\nhttps:\/\/expert-only.com\/en\/t-sql\/sql-server-pivot-query-example\/\n<\/div><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Tutorials on useful SQL Server queries<\/h3>\n\n\n\n<p>Here is a selection of some MS SQL tutorials with simple but useful queries.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/expert-only.com\/en\/t-sql\/sql-server-substring-function\/\">How to use the SQL Server substring function? With Examples<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/expert-only.com\/en\/t-sql\/insert-or-update-with-sql-server\/\">Two methods to perform an Insert Or Update with in T-SQL<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/expert-only.com\/en\/t-sql\/calculate-difference-between-two-dates\/\">How to calculate the difference between two dates with SQL Server ?<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>How to run multiple SELECT queries on the same SQL Server CTE? Is it possible to execute several selection queries on a CTE, i.e. to call a SQL Server CTE multiple times in the same stored procedure for example? <a class=\"mh-excerpt-more\" href=\"https:\/\/expert-only.com\/en\/t-sql\/call-a-sql-server-cte-multiple-times\/\" title=\"Call a SQL Server CTE multiple times and reuse the data\">&#8230;<\/a><\/p>\n<\/div>","protected":false},"author":1,"featured_media":10839,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[454],"tags":[],"class_list":{"0":"post-18294","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-t-sql"},"_links":{"self":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts\/18294","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/comments?post=18294"}],"version-history":[{"count":0,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts\/18294\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/media\/10839"}],"wp:attachment":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/media?parent=18294"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/categories?post=18294"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/tags?post=18294"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}