<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Steve Stedman</title>
	<atom:link href="http://stevestedman.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://stevestedman.com</link>
	<description>SQL Server Stuff</description>
	<lastBuildDate>Mon, 17 Jun 2013 16:00:39 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>What Do You Use CTEs for?</title>
		<link>http://stevestedman.com/2013/06/what-do-you-use-ctes-for/</link>
		<comments>http://stevestedman.com/2013/06/what-do-you-use-ctes-for/#comments</comments>
		<pubDate>Mon, 17 Jun 2013 16:00:39 +0000</pubDate>
		<dc:creator>SteveStedman</dc:creator>
				<category><![CDATA[CTE]]></category>
		<category><![CDATA[CTE Book]]></category>
		<category><![CDATA[Common Expressions]]></category>

		<guid isPermaLink="false">http://stevestedman.com/?p=2986</guid>
		<description><![CDATA[There are many great reasons to use Common Expressions, from derived table query re-use, to doing recursive queries and creating hierarchies to doing data paging, cleaner code, or de-duplication of data. I am curious what you are using CTE&#8217;s for? Please post a reply with the top things you use CTE&#8217;s for. Thanks!!]]></description>
				<content:encoded><![CDATA[<p>There are many great reasons to use Common Expressions, from derived table query re-use, to doing recursive queries and creating hierarchies to doing data paging, cleaner code, or de-duplication of data.</p>
<p>I am curious what you are using CTE&#8217;s for?</p>
<p>Please post a reply with the top things you use CTE&#8217;s for.</p>
<p>Thanks!!</p>
]]></content:encoded>
			<wfw:commentRss>http://stevestedman.com/2013/06/what-do-you-use-ctes-for/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>CTE Data Paging in a Procedure</title>
		<link>http://stevestedman.com/2013/06/cte-data-paging-in-a-procedure/</link>
		<comments>http://stevestedman.com/2013/06/cte-data-paging-in-a-procedure/#comments</comments>
		<pubDate>Sun, 16 Jun 2013 17:00:41 +0000</pubDate>
		<dc:creator>SteveStedman</dc:creator>
				<category><![CDATA[CTE]]></category>
		<category><![CDATA[CTE Book]]></category>
		<category><![CDATA[Common Table Expressions]]></category>
		<category><![CDATA[Data Paging]]></category>
		<category><![CDATA[END]]></category>
		<category><![CDATA[FETCH]]></category>
		<category><![CDATA[OFFSET]]></category>
		<category><![CDATA[Related Links]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://stevestedman.com/?p=3049</guid>
		<description><![CDATA[Day 15 of Common Table Expression Month (June) at SteveStedman.com, today we will be taking a look at data paging with CTE&#8217;s in a function. Yesterday we took a look at CTEs for Data Paging, today we will build on what we used yesterday. These queries will be using that database that was set up in [...]]]></description>
				<content:encoded><![CDATA[<p>Day 15 of Common Table Expression Month (June) at <a href="http://SteveStedman.com">SteveStedman.com</a>, today we will be taking a look at data paging with CTE&#8217;s in a function. Yesterday we took a look at CTEs for Data Paging, today we will build on what we used yesterday.</p>
<p>These queries will be using that database that was set up in a previous posting on the <a href="http://stevestedman.com/2013/06/sample-database-for-common-table-expressions/">CTE_DEMO Sample Database</a>, if you haven&#8217;t set up the sample database, download it and set it up now.</p>
<p>The concept of data paging is taking a large set of results and breaking it up into smaller pages of result sets. For instance if you search your favorite internet search engine for a term, you are usually shown results 1 to 20 of X where X is a very large number.  For instance page 1 is results 1 to 20 of 652,443 results.</p>
<h3>CTE Data Paging</h3>
<pre class="brush: sql; title: ; notranslate">

declare @pageNum as int;
declare @pageSize as int;
set @pageNum = 2;
set @pageSize = 10;

;WITH TablesAndColumns AS
(
SELECT OBJECT_NAME(sc.object_id) AS TableName,
 name AS ColumnName,
 ROW_NUMBER() OVER (ORDER BY OBJECT_NAME(sc.object_id)) AS RowNum
 FROM sys.columns sc
)
SELECT *
 FROM TablesAndColumns
 WHERE RowNum BETWEEN (@pageNum - 1) * @pageSize + 1
 AND @pageNum * @pageSize ;
</pre>
<p>Now lets wrap it in a procedure to simplify things.</p>
<pre class="brush: sql; title: ; notranslate">

CREATE PROCEDURE TablesAndColumnsPager @pageNum int, @pageSize int
AS
BEGIN
SET NOCOUNT ON;

;WITH TablesAndColumns AS
  (
SELECT OBJECT_NAME(sc.object_id) AS TableName,
  name AS ColumnName,
  ROW_NUMBER() OVER (ORDER BY OBJECT_NAME(sc.object_id)) AS RowNum
  FROM sys.columns sc
  )
  SELECT *
  FROM TablesAndColumns
  WHERE RowNum BETWEEN (@pageNum - 1) * @pageSize + 1
  AND @pageNum * @pageSize ;
END
</pre>
<p>Then to call the paging function it is a bit cleaner.</p>
<pre class="brush: sql; title: ; notranslate">

exec TablesAndColumnsPager 1, 10;
exec TablesAndColumnsPager 2, 10;
exec TablesAndColumnsPager 3, 10;

</pre>
<p><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px;">Which produces the following output.<br />
<a href="http://stevestedman.com/wp-content/uploads/DataPagingSproc1.jpg"><img class="aligncenter  wp-image-3062" alt="DataPagingSproc1" src="http://stevestedman.com/wp-content/uploads/DataPagingSproc1.jpg" width="440" height="492" /></a><br />
</span></p>
<h3>Related Links:</h3>
<ul>
<li><span style="line-height: 13px;"><a title="Books" href="http://stevestedman.com/books/">My Book on Common Table Expressions</a></span></li>
<li><a href="http://stevestedman.com/2013/06/sample-database-for-common-table-expressions/">cte_demo sample database</a></li>
<li><a href="http://stevestedman.com/2012/04/tsql-2012-offset-and-fetch/">TSQL 2012 &#8211; OFFSET and FETCH</a></li>
</ul>
<h3>Common Table Expressions Book</h3>
<p>If you enjoyed this posting, and want to learn more about common table expressions, please take a look at my book on CTE&#8217;s at Amazon.com. The book is titled Common Table Expressions - Joes 2 Pros® - A CTE Tutorial on Performance, Stored Procedures, Recursion, Nesting and the use of Multiple CTEs.<br />
<iframe style="width: 120px; height: 240px;" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;bc1=FFFFFF&amp;IS2=1&amp;npa=1&amp;bg1=FFFFFF&amp;fc1=000000&amp;lc1=0000FF&amp;t=wake2wakecom&amp;o=1&amp;p=8&amp;l=as4&amp;m=amazon&amp;f=ifr&amp;ref=ss_til&amp;asins=193966618X" height="240" width="320" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://stevestedman.com/2013/06/cte-data-paging-in-a-procedure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Week In Review &#8211; June 15th 2012</title>
		<link>http://stevestedman.com/2013/06/week-in-review-june-15th-2012/</link>
		<comments>http://stevestedman.com/2013/06/week-in-review-june-15th-2012/#comments</comments>
		<pubDate>Sat, 15 Jun 2013 16:00:07 +0000</pubDate>
		<dc:creator>SteveStedman</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Common Table Expression]]></category>
		<category><![CDATA[Database Health Reports]]></category>
		<category><![CDATA[Seven Hundredth]]></category>

		<guid isPermaLink="false">http://stevestedman.com/?p=3055</guid>
		<description><![CDATA[It has been a busy week at SteveStedman.com. Here is a quick summary of this weeks postings: June 14th - CTE Data Paging June 13th - Query To Simulate CPU Load June 12th &#8211; Nested CTE’s Gone Wild – The Video June 11th - Nested CTEs June 10th - Database Health Reports – Seven Hundred Downloads So Far June [...]]]></description>
				<content:encoded><![CDATA[<p>It has been a busy week at <a href="http://SteveStedman.com">SteveStedman.com</a>. Here is a quick summary of this weeks postings:</p>
<ul>
<li>June 14th - <a href="http://stevestedman.com/2013/06/cte-data-paging/">CTE Data Paging</a></li>
<li>June 13th - <a href="http://stevestedman.com/2013/06/query-to-simulate-cpu-load/">Query To Simulate CPU Load</a></li>
<li>June 12th &#8211; <a href="http://stevestedman.com/2013/06/nested-ctes-gone-wild/">Nested CTE’s Gone Wild – The Video</a></li>
<li>June 11th - <a href="http://stevestedman.com/2013/06/nested-ctes/">Nested CTEs</a></li>
<li>June 10th - <a href="http://stevestedman.com/2013/06/database-health-reports-seven-hundred-downloads-so-far/">Database Health Reports – Seven Hundred Downloads So Far</a></li>
<li>June 10th - <a href="http://stevestedman.com/2013/06/multiple-ctes-in-a-query/">Multiple CTEs in a Query</a></li>
<li>June 9th - <a href="http://stevestedman.com/2013/06/expanding-on-recursive-dates-cte/">Expanding on Recursive Dates CTE</a></li>
</ul>
<p>I think my favorite for the week was the <a href="http://DatabaseHealth.SteveStedman.com">Seven Hundredth download of the Database Health Reports </a>project. This project is really starting to take off. I am glad that people are using it and getting value out of it.</p>
<p>A successful week 2 of Common Table Expression month at <a href="http://SteveStedman.com">SteveStedman.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://stevestedman.com/2013/06/week-in-review-june-15th-2012/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CTE Data Paging</title>
		<link>http://stevestedman.com/2013/06/cte-data-paging/</link>
		<comments>http://stevestedman.com/2013/06/cte-data-paging/#comments</comments>
		<pubDate>Fri, 14 Jun 2013 16:00:28 +0000</pubDate>
		<dc:creator>SteveStedman</dc:creator>
				<category><![CDATA[CTE]]></category>
		<category><![CDATA[CTE Book]]></category>
		<category><![CDATA[Common Table Expressions]]></category>
		<category><![CDATA[FETCH]]></category>
		<category><![CDATA[OFFSET]]></category>
		<category><![CDATA[Related Links]]></category>
		<category><![CDATA[SELECT]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>

		<guid isPermaLink="false">http://stevestedman.com/?p=3040</guid>
		<description><![CDATA[Day 14 of Common Table Expression Month (June) at SteveStedman.com, today we will be taking a look at data paging with CTE&#8217;s and how it compares to the offset and fetch in T-SQL 2012. These queries will be using that database that was set up in a previous posting on the CTE_DEMO Sample Database, if you haven&#8217;t [...]]]></description>
				<content:encoded><![CDATA[<p>Day 14 of Common Table Expression Month (June) at <a href="http://SteveStedman.com">SteveStedman.com</a>, today we will be taking a look at data paging with CTE&#8217;s and how it compares to the offset and fetch in T-SQL 2012.</p>
<p>These queries will be using that database that was set up in a previous posting on the <a href="http://stevestedman.com/2013/06/sample-database-for-common-table-expressions/">CTE_DEMO Sample Database</a>, if you haven&#8217;t set up the sample database, download it and set it up now.</p>
<p>The concept of data paging is taking a large set of results and breaking it up into smaller pages of result sets. For instance if you search your favorite internet search engine for a term, you are usually shown results 1 to 20 of X where X is a very large number.  For instance page 1 is results 1 to 20 of 652,443 results.</p>
<h3>Data Paging &#8211; Before SQL 2012</h3>
<p>First lets take a look at a query with no data paging Shows all tables on this database, and all columns, and returns many rows.</p>
<pre class="brush: sql; title: ; notranslate">

SELECT OBJECT_NAME(sc.object_id) as TableName,
       name as ColumnName
  FROM sys.columns sc
ORDER BY OBJECT_NAME(sc.object_id);
</pre>
<p><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px;">When this is run we get 702 rows in the result set:<br />
<a href="http://stevestedman.com/wp-content/uploads/DataPagingCTE1.jpg"><img class="aligncenter  wp-image-3043" alt="DataPagingCTE1" src="http://stevestedman.com/wp-content/uploads/DataPagingCTE1.jpg" width="362" height="519" /></a><br />
</span></p>
<p>Now to introduce data paging with a CTE,  Here we have a CTE example to get data paging. This example assumes that the page size is 10 the first page would display the first 10 rows, the the second page would display rows 11 to 20, and the third page would display rows 21 to 30. Here we are using the ROW_NUMBER() function with the OVER clause for the windowing functionality to get the row number from the output. In a non-CTE query you can&#8217;t use ROW_NUMBER() in the where statement, but if it is wrapped in a CTE, and given a column alias we can then use it in the WHERE clause selecting from the CTE.</p>
<pre class="brush: sql; title: ; notranslate">

declare @pageNum as int;
declare @pageSize as int;
set @pageNum = 2;
set @pageSize = 10;

;WITH TablesAndColumns AS
(
SELECT OBJECT_NAME(sc.object_id) AS TableName,
 name AS ColumnName,
 ROW_NUMBER() OVER (ORDER BY OBJECT_NAME(sc.object_id)) AS RowNum
 FROM sys.columns sc
)
SELECT *
 FROM TablesAndColumns
 WHERE RowNum BETWEEN (@pageNum - 1) * @pageSize + 1
 AND @pageNum * @pageSize ;
</pre>
<p>When we run this we get the following results for page 2:</p>
<p style="text-align: center;"><a href="http://stevestedman.com/wp-content/uploads/DataPagingCTE2.jpg"><img class="aligncenter  wp-image-3044" alt="DataPagingCTE2" src="http://stevestedman.com/wp-content/uploads/DataPagingCTE2.jpg" width="437" height="261" /></a></p>
<p>Now if we change the @pageNum variable to be 3 we get the following:</p>
<p style="text-align: center;"><a href="http://stevestedman.com/wp-content/uploads/DataPagingCTE3.jpg"><img class="aligncenter  wp-image-3045" alt="DataPagingCTE3" src="http://stevestedman.com/wp-content/uploads/DataPagingCTE3.jpg" width="437" height="261" /></a></p>
<h3>SQL 2012 Data Paging</h3>
<p>If you are using SQL Server 2012, there is a new option added to the SELECT statement, this is called <a title="TSQL 2012 – OFFSET and FETCH" href="http://stevestedman.com/2012/04/tsql-2012-offset-and-fetch/">OFFSET and FETCH</a>. You have an option to do data paging without the CTE, the <a title="TSQL 2012 – OFFSET and FETCH" href="http://stevestedman.com/2012/04/tsql-2012-offset-and-fetch/">OFFSET and FETCH</a> option allows you to do the following:</p>
<pre class="brush: sql; title: ; notranslate">&lt;/pre&gt;
declare @pageNum as int;
declare @pageSize as int;
set @pageNum = 2;
set @pageSize = 10;

SELECT OBJECT_NAME(sc.object_id) AS TableName,
name AS ColumnName
 FROM sys.columns sc
 ORDER BY TableName
OFFSET (@pageNum - 1) * @pageSize ROWS FETCH NEXT @pageSize ROWS ONLY;
&lt;pre&gt;</pre>
<p>Which produces similar results for page 2 as the CTE version as shown here:</p>
<p style="text-align: center;"><a href="http://stevestedman.com/wp-content/uploads/DataPagingCTE4.jpg"><img class="aligncenter  wp-image-3046" alt="DataPagingCTE4" src="http://stevestedman.com/wp-content/uploads/DataPagingCTE4.jpg" width="381" height="264" /></a></p>
<h3>Which is Better?</h3>
<p>The only correct answer is &#8220;It Depends&#8221;.  It depends on a number of things. First if you are writing code that needs to run on an older version of SQL Server than 2012, then you can&#8217;t use the  <a title="TSQL 2012 – OFFSET and FETCH" href="http://stevestedman.com/2012/04/tsql-2012-offset-and-fetch/">OFFSET and FETCH</a> way 0f doing it, your best option is the CTE data paging. If you are running on only SQL Server 2012 or newer, then you have a choice. The size of your result set, the design of your tables, the number of JOINs in the query will all impact the overall performance. I would suggest if you are using SQL 2012 and you have a choice, code it both ways, and performance test it. See which runs best base on your specific query.</p>
<h3>Related Links:</h3>
<ul>
<li><span style="line-height: 13px;"><a title="Books" href="http://stevestedman.com/books/">My Book on Common Table Expressions</a></span></li>
<li><a href="http://stevestedman.com/2013/06/sample-database-for-common-table-expressions/">cte_demo sample database</a></li>
<li><a href="http://stevestedman.com/2012/04/tsql-2012-offset-and-fetch/">TSQL 2012 &#8211; OFFSET and FETCH</a></li>
</ul>
<h3>Common Table Expressions Book</h3>
<p>If you enjoyed this posting, and want to learn more about common table expressions, please take a look at my book on CTE&#8217;s at Amazon.com. The book is titled Common Table Expressions - Joes 2 Pros® - A CTE Tutorial on Performance, Stored Procedures, Recursion, Nesting and the use of Multiple CTEs.<br />
<iframe style="width: 120px; height: 240px;" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;bc1=FFFFFF&amp;IS2=1&amp;npa=1&amp;bg1=FFFFFF&amp;fc1=000000&amp;lc1=0000FF&amp;t=wake2wakecom&amp;o=1&amp;p=8&amp;l=as4&amp;m=amazon&amp;f=ifr&amp;ref=ss_til&amp;asins=193966618X" height="240" width="320" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://stevestedman.com/2013/06/cte-data-paging/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Query To Simulate CPU Load</title>
		<link>http://stevestedman.com/2013/06/query-to-simulate-cpu-load/</link>
		<comments>http://stevestedman.com/2013/06/query-to-simulate-cpu-load/#comments</comments>
		<pubDate>Fri, 14 Jun 2013 03:46:51 +0000</pubDate>
		<dc:creator>SteveStedman</dc:creator>
				<category><![CDATA[CTE]]></category>
		<category><![CDATA[CLUSTERED]]></category>
		<category><![CDATA[CPU]]></category>
		<category><![CDATA[GO]]></category>
		<category><![CDATA[Resource Governor]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[UNIQUEIDENTIFER]]></category>
		<category><![CDATA[UNIQUEIDENTIFIER]]></category>
		<category><![CDATA[VM]]></category>

		<guid isPermaLink="false">http://stevestedman.com/?p=3035</guid>
		<description><![CDATA[Quite often when working testing different performance measures from the Database Health Reports to testing Resource Governor configuration I end up in a situation where I need to emulate a high CPU load on my test SQL Server. In this case it is usually my desktop or a Hyper-V virtual machine, where I want to [...]]]></description>
				<content:encoded><![CDATA[<p>Quite often when working testing different performance measures from the <a href="http://databasehealth.stevestedman.com">Database Health Reports</a> to testing Resource Governor configuration I end up in a situation where I need to emulate a high CPU load on my test SQL Server. In this case it is usually my desktop or a Hyper-V virtual machine, where I want to see how things will work if I had a nearly 100% CPU load. In the real world you would just have to get millions of users to visit your website that has a SQL Server backend, that its not that easy in my development / test lab.</p>
<p>Here is that I came up with for a plan. Keeping in mind the goal here is to write queries that will use up as much CPU as possible. This is counter-intuitive, completely against everything that I practice on a daily basis, but here goes.</p>
<p>First create a table with poor design. Using UNIQUEIDENTIFIERS for a primary key and a foreign key (parent_id) is probably ugly enough.</p>
<pre class="brush: sql; title: ; notranslate">

CREATE TABLE SplitThrash
(
 id UNIQUEIDENTIFIER default newid(),
 parent_id UNIQUEIDENTIFIER default newid(),
 name VARCHAR(50) default cast(newid() as varchar(50))
);

</pre>
<p>Next we fill the table up with lots and lots of rows, specifically 1,000,000 rows, remember here the goal is to simulate CPU load. If this isn&#8217;t enough I often times run this script several times. Keep in mind the GO statement followed by a number says to execute the batch that many times.</p>
<pre class="brush: sql; title: ; notranslate">

SET NOCOUNT ON;
INSERT INTO SplitThrash DEFAULT VALUES;
GO  1000000

</pre>
<p>Next, this part makes me just feel nasty. Create a CLUSTERED index on the table that we just filled up, and cluster on BOTH columns that were UNIQUEIDENTIFIERS.</p>
<pre class="brush: sql; title: ; notranslate">

CREATE CLUSTERED INDEX [ClusteredSplitThrash] ON [dbo].[SplitThrash]
(
 [id] ASC,
 [parent_id] ASC
);

</pre>
<p>At this point is is a bit ugly, but it still doesn&#8217;t use much memory. You are probably wondering why I called the table split thrash. I gave it this name so that updating the UNIQUEIDENTIFER would cause as many page splits or new page allocations as possible. So we update the parent_id which is part of the clustered index</p>
<pre class="brush: sql; title: ; notranslate">&lt;/pre&gt;
UPDATE SplitThrash
SET parent_id = newid(), id = newid();
GO 100
&lt;pre&gt;</pre>
<p>This update statement causes chaos in the page structure for the table as updating the unique identifiers causes quite a bit of processor work.</p>
<p>On my wimpy VM for this development environment I need to repeat this entire process creating 4 or 5 tables, and doing the update in 4 or 5 SSMS windows in order to use up all of the CPU on the database.</p>
<p>Don&#8217;t try this on a production system, but it is a great test to run on a development server.</p>
<h3>See Also:</h3>
<p>If you like this you might also like my article on how to <a title="Nested CTE’s Gone Wild – The Video" href="http://stevestedman.com/2013/06/nested-ctes-gone-wild/">use up all of your memory with a common table expression</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://stevestedman.com/2013/06/query-to-simulate-cpu-load/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Nested CTE&#8217;s Gone Wild &#8211; The Video</title>
		<link>http://stevestedman.com/2013/06/nested-ctes-gone-wild/</link>
		<comments>http://stevestedman.com/2013/06/nested-ctes-gone-wild/#comments</comments>
		<pubDate>Wed, 12 Jun 2013 16:00:51 +0000</pubDate>
		<dc:creator>SteveStedman</dc:creator>
				<category><![CDATA[CTE]]></category>
		<category><![CDATA[CTE Book]]></category>
		<category><![CDATA[Common Table Expressions]]></category>
		<category><![CDATA[Related Links]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[TB]]></category>

		<guid isPermaLink="false">http://stevestedman.com/?p=3011</guid>
		<description><![CDATA[Day 12 of Common Table Expression Month (June) at SteveStedman.com, today we will be taking a look at how to use multiple nested CTEs in a query to use up all the memory on your SQL Server. These queries will be using that database that was set up in a previous posting on the CTE_DEMO Sample Database, [...]]]></description>
				<content:encoded><![CDATA[<p>Day 12 of Common Table Expression Month (June) at <a href="http://SteveStedman.com">SteveStedman.com</a>, today we will be taking a look at how to use multiple nested CTEs in a query to use up all the memory on your SQL Server.</p>
<p>These queries will be using that database that was set up in a previous posting on the <a href="http://stevestedman.com/2013/06/sample-database-for-common-table-expressions/">CTE_DEMO Sample Database</a>, if you haven&#8217;t set up the sample database, download it and set it up now.</p>
<h3>How to use up all of your SQL Server available memory with a single CTE query</h3>
<p>The article could be named, &#8220;How to use up all of your SQL Server available memory with a single CTE query.&#8221; Another name for the article could just be &#8220;SQL Server Bug Report&#8221; depending on how you look at it.</p>
<p>When presenting unleashing Common Table Expressions at SQL Saturday a while back, I was asked a couple of great questions that I didn&#8217;t know the answer to. So I did the research and tracked it down:</p>
<p>1. How many levels of recursion can you have in a CTE?</p>
<p>2. How many levels of nesting can you have in a CTE?</p>
<p>So I started doing the research and doing some testing to figure it out.</p>
<h3>How many levels of recursion can you have in a CTE?</h3>
<p>This is the easier one to answer between the two questions. The answer is, you can have more levels of recursion that you would ever need for standard recursion. I have tested CTEs with up to 1 million levels of recursion, and the have performed pretty well. If you are writing queries that need more than 1 million levels of recursion, perhaps you should take a look at a different approach.</p>
<h3>How many levels of nesting can you have in a CTE?</h3>
<p>This is where it gets really interesting. SQL Server does a really good job with overall performance on <a href="http://stevestedman.com/category/classes/cte/">CTE</a>s, but where it completely breaks down is on deep nested <a href="http://stevestedman.com/category/classes/cte/">CTE</a> queries. By deep nested I mean more than a thousand or two thousand. To answer the question of how many levels can you have, I would answer this as you can nest more than you would ever really need. If you really need more than a thousand levels of nesting in a <a href="http://stevestedman.com/category/classes/cte/">CTE</a>, you might want to rethink your approach.</p>
<p>On SQL Server 2005 the limit is 255. But in SQL Server 2008 and newer this limit was extended, and appears to not have a fixed limit, rather the limit is based on the amount of memory available for the query to use.</p>
<p>So to build the crazy <a href="http://stevestedman.com/category/classes/cte/">CTE</a>, I used excel to build out several thousands of rows of nested <a href="http://stevestedman.com/category/classes/cte/">CTE</a>s. One calling another, calling the next, and so on. What I found was that this was a very easy way to use up almost all the memory on your database. DO NOT TRY THIS ON A PRODUCTION DATABASE. The reason that DBAs and developers have test or development databases is to play around with things that may be dangerous on a production server. This is one that you could try on a test server.</p>
<p>The other interesting thing that the query does when it uses up all the memory, somehow it dumps some of the connections that are currently active on the SQL Server at that point.</p>
<p>Watch the video to find out how a nested <a href="http://stevestedman.com/category/classes/cte/">CTE</a> query could use up all of the memory on your SQL Server.</p>
<p><iframe src="http://www.youtube.com/embed/KOvqUjE6714" height="315" width="560" allowfullscreen="" frameborder="0"></iframe></p>
<p>If anyone has a test server with 512GB, or 1TB of available, memory, I would love to see how this type of query performs. Give it a try and let me know.</p>
<p>You can download the script <a href="http://stevestedman.com/wp-content/uploads/NestedCTE.zip">NestedCTE.zip here</a>. The zip file contains 2 files, one called CTE.sql, and one called CTE2500.sql.  The 2500 version is the one that I used in the demo, and the CTE.sql has 32767 nestings.  I would love to see the bigger on run on a server with a TB or more of memory to see how it performs.</p>
<h3>Related Links:</h3>
<ul>
<li><span style="line-height: 13px;"><a title="Books" href="http://stevestedman.com/books/">My Book on Common Table Expressions</a><br />
</span></li>
<li><a href="http://stevestedman.com/2013/06/sample-database-for-common-table-expressions/">cte_demo sample database</a></li>
</ul>
<h3>Common Table Expressions Book</h3>
<p>If you enjoyed this posting, and want to learn more about common table expressions, please take a look at my book on CTE&#8217;s at Amazon.com. The book is titled Common Table Expressions - Joes 2 Pros® - A CTE Tutorial on Performance, Stored Procedures, Recursion, Nesting and the use of Multiple CTEs.<br />
<iframe style="width: 120px; height: 240px;" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;bc1=FFFFFF&amp;IS2=1&amp;npa=1&amp;bg1=FFFFFF&amp;fc1=000000&amp;lc1=0000FF&amp;t=wake2wakecom&amp;o=1&amp;p=8&amp;l=as4&amp;m=amazon&amp;f=ifr&amp;ref=ss_til&amp;asins=193966618X" height="240" width="320" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://stevestedman.com/2013/06/nested-ctes-gone-wild/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Nested CTEs</title>
		<link>http://stevestedman.com/2013/06/nested-ctes/</link>
		<comments>http://stevestedman.com/2013/06/nested-ctes/#comments</comments>
		<pubDate>Tue, 11 Jun 2013 16:00:54 +0000</pubDate>
		<dc:creator>SteveStedman</dc:creator>
				<category><![CDATA[CTE]]></category>
		<category><![CDATA[CTE Book]]></category>
		<category><![CDATA[Common Table Expressions]]></category>
		<category><![CDATA[Related Links]]></category>
		<category><![CDATA[Russian Nesting Dolls]]></category>
		<category><![CDATA[Stored Procedures]]></category>

		<guid isPermaLink="false">http://stevestedman.com/?p=3009</guid>
		<description><![CDATA[Day 11 of Common Table Expression Month (June) at SteveStedman.com, today we will be taking a look at how to use multiple nested CTEs in a query. These queries will be using that database that was set up in a previous posting on the CTE_DEMO Sample Database, if you haven&#8217;t set up the sample database, download it [...]]]></description>
				<content:encoded><![CDATA[<p>Day 11 of Common Table Expression Month (June) at <a href="http://SteveStedman.com">SteveStedman.com</a>, today we will be taking a look at how to use multiple nested CTEs in a query.</p>
<p>These queries will be using that database that was set up in a previous posting on the <a href="http://stevestedman.com/2013/06/sample-database-for-common-table-expressions/">CTE_DEMO Sample Database</a>, if you haven&#8217;t set up the sample database, download it and set it up now.</p>
<h3>Russian Nesting Dolls</h3>
<p>If you have ever seen the Matryoshka dolls known as the Russian nesting dolls or babushka dolls they are very interesting. They start with a large wooden doll that when opened contains a slightly smaller doll, then inside of that one an even smaller doll. These dolls often have five to eight dolls nested inside of each other.</p>
<p>The interesting thing about these dolls is that they have one specific way that they can all fit together; the smallest doll must be the first one put inside of the next smallest. If you were to lose one of the medium dolls, they could still be placed together; there would just be some extra space inside.</p>
<p>Nested CTEs often remind me of the Russian nesting dolls. Think of the first CTE in a multiple CTE query as the smallest doll. That first CTE can’t reference any other CTEs, much like the smallest doll can’t fit any other dolls inside of it.</p>
<p>Think of the second CTE in a multiple CTE query as the second smallest doll in the Russian dolls. It can only have one doll fit inside of it. CTEs are similar in that the only CTE that can be referenced by the second CTE in a multiple CTE query is the first CTE.</p>
<p>The third CTE is like the third smallest Russian doll. The third smallest doll can only have the smallest or second smallest doll placed inside of it. With the third CTE it can only access the first or the second CTE declared, and not any of the CTEs declared later.</p>
<p>The same concept applies for all of the CTEs in a nested CTE query. Any CTE query can access the CTEs declared prior to that one, but not the ones after.</p>
<h3>Nested CTEs</h3>
<p>Take an example of a multiple CTE query with 4 CTEs as follows with the … being replaced with a T-SQL query.</p>
<pre class="brush: sql; title: ; notranslate">

;WITH CTE1 AS
  ( .... ),

CTE2 AS
  ( .... ),

CTE3 AS
  ( .... ),

CTE4 AS
  ( .... )

SELECT *
    FROM CTE4;

</pre>
<p>&nbsp;</p>
<h3>Related Links:</h3>
<ul>
<li><span style="line-height: 13px;"><a title="Books" href="http://stevestedman.com/books/">My Book on Common Table Expressions</a><br />
</span></li>
<li><a href="http://stevestedman.com/2013/06/sample-database-for-common-table-expressions/">cte_demo sample database</a></li>
</ul>
<h3>Common Table Expressions Book</h3>
<p>If you enjoyed this posting, and want to learn more about common table expressions, please take a look at my book on CTE&#8217;s at Amazon.com. The book is titled Common Table Expressions - Joes 2 Pros® - A CTE Tutorial on Performance, Stored Procedures, Recursion, Nesting and the use of Multiple CTEs.<br />
<iframe style="width: 120px; height: 240px;" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;bc1=FFFFFF&amp;IS2=1&amp;npa=1&amp;bg1=FFFFFF&amp;fc1=000000&amp;lc1=0000FF&amp;t=wake2wakecom&amp;o=1&amp;p=8&amp;l=as4&amp;m=amazon&amp;f=ifr&amp;ref=ss_til&amp;asins=193966618X" height="240" width="320" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://stevestedman.com/2013/06/nested-ctes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Database Health Reports &#8211; Seven Hundred Downloads So Far</title>
		<link>http://stevestedman.com/2013/06/database-health-reports-seven-hundred-downloads-so-far/</link>
		<comments>http://stevestedman.com/2013/06/database-health-reports-seven-hundred-downloads-so-far/#comments</comments>
		<pubDate>Mon, 10 Jun 2013 16:42:14 +0000</pubDate>
		<dc:creator>SteveStedman</dc:creator>
				<category><![CDATA[Database Health]]></category>
		<category><![CDATA[Database Health Reports]]></category>
		<category><![CDATA[New Inefficient Indexes]]></category>
		<category><![CDATA[Raving Fans]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://stevestedman.com/?p=2979</guid>
		<description><![CDATA[Since the initial release of the Database Health Reports project last September, there have been over 700 downloads of the application at this point Beta6 is going strong. First I would like to say Thank You to everyone using it so far. Beta 6 introduced a few new features, but mostly focused on overall stability and bug fixing. [...]]]></description>
				<content:encoded><![CDATA[<p>Since the initial release of the <a href="http://DatabaseHealth.SteveStedman.com">Database Health Reports</a> project last September, there have been over 700 <a href="http://databasehealth.stevestedman.com/download/" target="_blank">downloads</a> of the application at this point <a href="http://databasehealth.stevestedman.com/download/" target="_blank">Beta6</a> is going strong.</p>
<p>First I would like to say Thank You to everyone using it so far.</p>
<p>Beta 6 introduced a few new features, but mostly focused on overall stability and bug fixing.</p>
<ul>
<li>New Inefficient Indexes report added. Useful to find indexes that aren’t being used.</li>
<li>Scrollbar added to the <a title="Historic Waits" href="http://databasehealth.stevestedman.com/historic-db-reporting/historic-waits/">historic waits report</a> to allow for easier browsing of wait stats.</li>
<li>Overall improved CTRL-C and CTRL-A clipboard support.</li>
<li>Adding a setting dialog to consolidate some of the basic settings.</li>
<li>Added a threshold setting (to the new setting dialog) to set the threshold to search on the big clustered indexes report.</li>
<li>Added sorting to all the columns in all the grids.</li>
<li>Added the application name into the connect string.</li>
<li>Improved the call to check for updates when the application starts.</li>
<li>Adding another warning to the <a title="Database Overview" href="http://databasehealth.stevestedman.com/database-overview/">database overview panel</a> for huge log files.</li>
<li>Added additional wait type documentation.</li>
<li>Improved error handling.</li>
<li>Added the update every X seconds functionality to the <a title="Connections" href="http://databasehealth.stevestedman.com/database-overview/connections/">database connections report</a>, this includes a setting in the setting dialog to change the every X seconds interval. If you don’t want it to update, just set it to a very large number.</li>
<li>New update interval settings for the database overview and server overview panels.</li>
<li>Adding Historic Plan Cache Hit Ratio Chart to the <a title="Historic DB Reporting" href="http://databasehealth.stevestedman.com/historic-db-reporting/">Historic Reporting</a> section.</li>
</ul>
<p>Still my favorite part of the overall product is the historic wait time monitoring. Once historic monitoring is turned, it records data about what may having been causing problems at some point in time. This way when someone make a comment like &#8220;The database appeared slow yesterday at 4:25am&#8221;, you have the ability to go find out why it may have been slow.</p>
<p style="text-align: center;"><a href="http://stevestedman.com/wp-content/uploads/HistoricWaits.jpg"><img class="aligncenter  wp-image-2984" alt="HistoricWaits" src="http://stevestedman.com/wp-content/uploads/HistoricWaits.jpg" width="466" height="258" /></a></p>
<p>On June 6th I received a nice comment on the <a href="http://databasehealth.stevestedman.com/about/raving-fans/">Raving Fans page</a>. This page was set up to share what people have to say about this application. Since the application is free of charge the only thing I ask is for someone to share what they find with the application:</p>
<p style="text-align: center;"><a href="http://databasehealth.stevestedman.com/about/raving-fans/"><img class="aligncenter size-full wp-image-2980" alt="RavingFan1" src="http://stevestedman.com/wp-content/uploads/RavingFan1.jpg" width="566" height="132" /></a></p>
<p><a href="http://DatabaseHealth.SteveStedman.com">Database Health Reports</a> is a free application that I provide to the SQL Server community to help analyze and fix performance problems on your MS Sql Server.</p>
]]></content:encoded>
			<wfw:commentRss>http://stevestedman.com/2013/06/database-health-reports-seven-hundred-downloads-so-far/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multiple CTEs in a Query</title>
		<link>http://stevestedman.com/2013/06/multiple-ctes-in-a-query/</link>
		<comments>http://stevestedman.com/2013/06/multiple-ctes-in-a-query/#comments</comments>
		<pubDate>Mon, 10 Jun 2013 16:00:56 +0000</pubDate>
		<dc:creator>SteveStedman</dc:creator>
				<category><![CDATA[CTE]]></category>
		<category><![CDATA[CTE Book]]></category>
		<category><![CDATA[Common Table Expressions]]></category>
		<category><![CDATA[Related Links]]></category>
		<category><![CDATA[SELECT]]></category>
		<category><![CDATA[Single Statement]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[UNION]]></category>

		<guid isPermaLink="false">http://stevestedman.com/?p=3007</guid>
		<description><![CDATA[Day 10 of Common Table Expression Month (June) at SteveStedman.com, today we will be taking a look at how to use multiple CTEs in a query. These queries will be using that database that was set up in a previous posting on the CTE_DEMO Sample Database, if you haven&#8217;t set up the sample database, download it and [...]]]></description>
				<content:encoded><![CDATA[<p>Day 10 of Common Table Expression Month (June) at <a href="http://SteveStedman.com">SteveStedman.com</a>, today we will be taking a look at how to use multiple CTEs in a query.</p>
<p>These queries will be using that database that was set up in a previous posting on the <a href="http://stevestedman.com/2013/06/sample-database-for-common-table-expressions/">CTE_DEMO Sample Database</a>, if you haven&#8217;t set up the sample database, download it and set it up now.</p>
<p>&nbsp;</p>
<p>One of the questions that comes up when discussing <a title="CTE Scope" href="http://stevestedman.com/2013/06/cte-scope/">CTE Scope</a> is can I do multiple CTEs. The answer is yes you can do multiple CTEs but the s<a title="CTE Scope" href="http://stevestedman.com/2013/06/cte-scope/">cope</a> is is still constrained to a single SQL Statement.</p>
<h3>Multiple CTEs in a Single Statement</h3>
<p>Lets take a look when multiple CTEs in a single statement might be useful. Take the example of trying to generate random names in order to fill up tables in a test database to simulate a full database during the development phase of a new project. This example is explained in much further detail in <a title="Books" href="http://stevestedman.com/books/">chapter 6 in my Book on Common Table Expressions</a>. Lets take a look here at this example from my SQL Saturday presentation. The following is a CTE that returns a list of first names.</p>
<pre class="brush: sql; title: ; notranslate">

;WITH Fnames (Name) AS
(

SELECT 'John'
 UNION
 SELECT 'Mary'
 UNION
 SELECT 'Bill'

)
SELECT F.Name FirstName
 FROM Fnames F;

</pre>
<p>When run we see the following:</p>
<p><a href="http://stevestedman.com/wp-content/uploads/MultipleCTEs1.jpg"><img class="aligncenter size-full wp-image-3020" alt="MultipleCTEs1" src="http://stevestedman.com/wp-content/uploads/MultipleCTEs1.jpg" width="401" height="296" /></a></p>
<p>&nbsp;</p>
<p>Now if we want to expand on that we can add a second CTE for last names and CROSS JOIN the results of the two CTEs. A refresher on CROSS JOIN, the CROSS JOIN takes every row from one side and matches it up with every rows for the other side, with no ON clause. This effectively creates a Cartesian product of the two tables, or joins up every possible combination.</p>
<pre class="brush: sql; title: ; notranslate">

;WITH Fnames (Name) AS
(
SELECT 'John'
 UNION
 SELECT 'Mary'
 UNION
 SELECT 'Bill'
 ),

Lnames (Name) AS
(
SELECT 'Smith'
 UNION
 SELECT 'Gibb'
 UNION
 SELECT 'Jones'
 )

SELECT F.Name AS FirstName, L.Name AS LastName
 FROM Fnames AS F
 CROSS JOIN Lnames AS L;

</pre>
<p style="text-align: center;"><a href="http://stevestedman.com/wp-content/uploads/MultipleCTEs2.jpg"><img class="aligncenter  wp-image-3021" alt="MultipleCTEs2" src="http://stevestedman.com/wp-content/uploads/MultipleCTEs2.jpg" width="406" height="335" /></a></p>
<p style="text-align: center;">
<p>Here you will notice that the initial CTE is separated from the new CTE with a comma, and that the second CTE doesn&#8217;t start with the WITH keyword. Then in the final SELECT statement it just references both of the CTE statements declared above. When run we see the following results.</p>
<p><a href="http://stevestedman.com/wp-content/uploads/MultipleCTEs3.jpg"><img class="aligncenter size-full wp-image-3022" alt="MultipleCTEs3" src="http://stevestedman.com/wp-content/uploads/MultipleCTEs3.jpg" width="301" height="335" /></a></p>
<p>&nbsp;</p>
<p>Here you can see that every first name is joined up with every last name, with two input tables of 3 rows each the result set has 3&#215;3 or 9 rows of output.</p>
<p>You could also add a third CTE with middle names, and possibly a 4th with login names, and very quickly end up with a very large result set multiplying each time there is another cross join added.</p>
<p>&nbsp;</p>
<h3>Related Links:</h3>
<ul>
<li><span style="line-height: 13px;"><a title="Books" href="http://stevestedman.com/books/">My Book on Common Table Expressions</a><br />
</span></li>
<li><a href="http://stevestedman.com/2013/06/sample-database-for-common-table-expressions/">cte_demo sample database</a></li>
<li><a title="CTE Scope" href="http://stevestedman.com/2013/06/cte-scope/">CTE Scope</a></li>
</ul>
<h3>Common Table Expressions Book</h3>
<p>If you enjoyed this posting, and want to learn more about common table expressions, please take a look at my book on CTE&#8217;s at Amazon.com. The book is titled Common Table Expressions - Joes 2 Pros® - A CTE Tutorial on Performance, Stored Procedures, Recursion, Nesting and the use of Multiple CTEs.<br />
<iframe style="width: 120px; height: 240px;" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;bc1=FFFFFF&amp;IS2=1&amp;npa=1&amp;bg1=FFFFFF&amp;fc1=000000&amp;lc1=0000FF&amp;t=wake2wakecom&amp;o=1&amp;p=8&amp;l=as4&amp;m=amazon&amp;f=ifr&amp;ref=ss_til&amp;asins=193966618X" height="240" width="320" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://stevestedman.com/2013/06/multiple-ctes-in-a-query/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Expanding on Recursive Dates CTE</title>
		<link>http://stevestedman.com/2013/06/expanding-on-recursive-dates-cte/</link>
		<comments>http://stevestedman.com/2013/06/expanding-on-recursive-dates-cte/#comments</comments>
		<pubDate>Sun, 09 Jun 2013 16:00:05 +0000</pubDate>
		<dc:creator>SteveStedman</dc:creator>
				<category><![CDATA[CTE]]></category>
		<category><![CDATA[CTE Book]]></category>
		<category><![CDATA[Anchor Query]]></category>
		<category><![CDATA[Common Table Expressions]]></category>
		<category><![CDATA[Recursive Query]]></category>
		<category><![CDATA[Recursive Review]]></category>
		<category><![CDATA[Related Links]]></category>
		<category><![CDATA[Stored Procedures]]></category>
		<category><![CDATA[Thanks Martyn]]></category>

		<guid isPermaLink="false">http://stevestedman.com/?p=2916</guid>
		<description><![CDATA[Day 9 of Common Table Expression Month (June) at SteveStedman.com, today I will be building on the intro to recursive CTEs from two days ago and on showing how a recursive CTE can be used to calculate information about dates of the year from yesterday. This would be useful if you were trying to build a calendar. These queries [...]]]></description>
				<content:encoded><![CDATA[<p>Day 9 of Common Table Expression Month (June) at <a href="http://SteveStedman.com">SteveStedman.com</a>, today I will be building on the <a title="Introduction to Recursive CTEs" href="http://stevestedman.com/2013/06/introduction-to-recursive-ctes/">intro to recursive CTEs</a> from two days ago and on <a title="Recursive CTE for Dates In A Year" href="http://stevestedman.com/2013/06/recursive-cte-for-dates-in-a-year/">showing how a recursive CTE can be used to calculate information about dates of the year</a> from yesterday. This would be useful if you were trying to build a calendar.</p>
<p>These queries will be using that database that was set up in a previous posting on the <a href="http://stevestedman.com/2013/06/sample-database-for-common-table-expressions/">CTE_DEMO Sample Database</a>, if you haven&#8217;t set up the sample database, download it and set it up now.</p>
<h3>Recursive Review</h3>
<p>Yesterday&#8217;s topic was the<a title="Introduction to Recursive CTEs" href="http://stevestedman.com/2013/06/introduction-to-recursive-ctes/"> introduction to recursive CTE&#8217;s.</a></p>
<p><a title="Introduction to Recursive CTEs" href="http://stevestedman.com/2013/06/introduction-to-recursive-ctes/"><img alt="RecursiveRevew" src="http://stevestedman.com/wp-content/uploads/RecursiveRevew.jpg" width="615" height="373" /></a></p>
<p>In the introduction to recursive CTE&#8217;s we covered the declaration of the CTE, the Anchor Query which starts the recursive process, the Recursive Query which continues the recursion, and the Query that calls the CTE.</p>
<h3>Dates CTE Review</h3>
<p>In the following picture, the CTE is named Dates, the anchor query start out by just selecting January 1st of 2013. Next the recursive part selects CalendarDate from the Dates CTE and it adds a single day to it. This all continues recursively as long as the date is less than January 1st 2014.</p>
<p><a href="http://stevestedman.com/wp-content/uploads/RecursiveDates1.jpg"><img alt="RecursiveDates1" src="http://stevestedman.com/wp-content/uploads/RecursiveDates1.jpg" width="570" height="291" /></a></p>
<h3>Adding In More Details</h3>
<p>For today&#8217;s example the CTE will be exactly the same as yesterday, but the query calling it is different. The part highlighted below shows the difference from yesterday.</p>
<p style="text-align: center;"><a href="http://stevestedman.com/wp-content/uploads/MoreRecursiveDates1.jpg"><img class="aligncenter  wp-image-2999" alt="MoreRecursiveDates1" src="http://stevestedman.com/wp-content/uploads/MoreRecursiveDates1.jpg" width="606" height="418" /></a></p>
<p style="text-align: left;">When run we get the following output:</p>
<p style="text-align: center;"><a href="http://stevestedman.com/wp-content/uploads/MoreRecursiveDates4.jpg"><img class="aligncenter  wp-image-3003" alt="MoreRecursiveDates4" src="http://stevestedman.com/wp-content/uploads/MoreRecursiveDates4.jpg" width="679" height="370" /></a></p>
<p style="text-align: left;">Next I borrow part of the date formatting from @DevonDBA from his post at <a href="http://devondba.blogspot.co.uk/2013/06/create-table-of-dates-showing-holidays.html">http://devondba.blogspot.co.uk/2013/06/create-table-of-dates-showing-holidays.html</a>, and slightly modify it as shown below. Thanks Martyn.</p>
<p style="text-align: center;"><a href="http://stevestedman.com/wp-content/uploads/MoreRecursiveDates2.jpg"><img class="aligncenter  wp-image-3001" alt="MoreRecursiveDates2" src="http://stevestedman.com/wp-content/uploads/MoreRecursiveDates2.jpg" width="511" height="471" /></a></p>
<p style="text-align: left;">Now we can see if the day that we are looking at is a weekday or a weekend as shown here:</p>
<p style="text-align: center;"><a href="http://stevestedman.com/wp-content/uploads/MoreRecursiveDates3.jpg"><img class="aligncenter  wp-image-3002" alt="MoreRecursiveDates3" src="http://stevestedman.com/wp-content/uploads/MoreRecursiveDates3.jpg" width="518" height="493" /></a></p>
<p style="text-align: left;">I hope you are enjoying CTE Month at <a href="http://SteveStedman.com">SteveStedman.com</a>.</p>
<h3>Related Links:</h3>
<ul>
<li><span style="line-height: 13px;"><a title="Books" href="http://stevestedman.com/books/">My Book on Common Table Expressions</a><br />
</span></li>
<li><a href="http://stevestedman.com/2013/06/sample-database-for-common-table-expressions/">cte_demo sample database</a></li>
<li><a title="Recursive CTE for Dates In A Year" href="http://stevestedman.com/2013/06/recursive-cte-for-dates-in-a-year/">Recursive CTE for Dates In A Year</a></li>
<li><a title="Introduction to Recursive CTEs" href="http://stevestedman.com/2013/06/introduction-to-recursive-ctes/">Introduction to Recursive CTEs</a></li>
</ul>
<h3>Common Table Expressions Book</h3>
<p>If you enjoyed this posting, and want to learn more about common table expressions, please take a look at my book on CTE&#8217;s at Amazon.com. The book is titled Common Table Expressions - Joes 2 Pros® - A CTE Tutorial on Performance, Stored Procedures, Recursion, Nesting and the use of Multiple CTEs.<br />
<iframe style="width: 120px; height: 240px;" src="http://rcm.amazon.com/e/cm?lt1=_blank&amp;bc1=FFFFFF&amp;IS2=1&amp;npa=1&amp;bg1=FFFFFF&amp;fc1=000000&amp;lc1=0000FF&amp;t=wake2wakecom&amp;o=1&amp;p=8&amp;l=as4&amp;m=amazon&amp;f=ifr&amp;ref=ss_til&amp;asins=193966618X" height="240" width="320" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://stevestedman.com/2013/06/expanding-on-recursive-dates-cte/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 1.757 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2013-06-18 14:06:15 -->

<!-- Compression = gzip -->