<?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>Diane McNurlan - My life with SQL ServerT-SQL | Diane McNurlan &#8211; My life with SQL Server</title>
	<atom:link href="http://www.dianemcnurlan.com/category/t-sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dianemcnurlan.com</link>
	<description></description>
	<lastBuildDate>Mon, 17 Oct 2011 02:50:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Fun and Joy with Optional Search Parameters</title>
		<link>http://www.dianemcnurlan.com/2011/03/fun-and-joy-with-optional-search-parameters/</link>
		<comments>http://www.dianemcnurlan.com/2011/03/fun-and-joy-with-optional-search-parameters/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 04:28:46 +0000</pubDate>
		<dc:creator>Diane McNurlan</dc:creator>
				<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://www.dianemcnurlan.com/2011/03/fun-and-joy-with-optional-search-parameters/</guid>
		<description><![CDATA[The past few weeks I&#8217;ve been writing stored procedures that use optional search parameters. Since this subject has been written about at length by many other SQL folks, with articles that have been very helpful to me, I decided to list the resources here on my blog. Dynamic Search Conditions in T-SQL &#8211; Version for...]]></description>
			<content:encoded><![CDATA[<p>The past few weeks I&#8217;ve been writing stored procedures that use optional search parameters. Since this subject has been written about at length by many other SQL folks, with articles that have been very helpful to me, I decided to list the resources here on my blog. </p>
<p><a href="http://www.sommarskog.se/dyn-search-2005.html">Dynamic Search Conditions in T-SQL &#8211; Version for SQL 2005 and Earlier by Erland Sommarskog</a> </p>
<p><a href="http://www.sommarskog.se/dyn-search-2008.html">Dynamic Search Conditions in T-SQL Version for SQL 2008 (SP1 CU5 and later) by Erland Sommarskog</a> </p>
<p><a href="http://blogs.msdn.com/b/bartd/archive/2009/05/03/sometimes-the-simplest-solution-isn-t-the-best-solution-the-all-in-one-search-query.aspx">Sometimes the Simplest Solution Isn&#8217;t the Best Solution by Bart Duncan</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dianemcnurlan.com/2011/03/fun-and-joy-with-optional-search-parameters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The two things you need to know about outer joins</title>
		<link>http://www.dianemcnurlan.com/2010/04/the-two-things-you-need-to-know-about-outer-joins/</link>
		<comments>http://www.dianemcnurlan.com/2010/04/the-two-things-you-need-to-know-about-outer-joins/#comments</comments>
		<pubDate>Mon, 05 Apr 2010 15:31:00 +0000</pubDate>
		<dc:creator>Diane McNurlan</dc:creator>
				<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://www.dianemcnurlan.com/2010/04/the-two-things-you-need-to-know-about-outer-joins/</guid>
		<description><![CDATA[Today I’ll discuss two very important items to keep in mind when coding with an outer join.&#160; These issues apply to both the left and right outer join. Join order matters – with an inner join, the join order does not affect the results set.&#160; The SELECT statement returns the same number of rows regardless...]]></description>
			<content:encoded><![CDATA[<p>Today I’ll discuss two very important items to keep in mind when coding with an outer join.&#160; These issues apply to both the left and right outer join.</p>
<p><strong>Join order matters</strong> – with an inner join, the join order does not affect the results set.&#160; The SELECT statement returns the same number of rows regardless of the order in which the tables are listed.&#160; But that is not the case with an outer join.&#160; Here is an example from the AdventureWorks sample database.</p>
<p>First I’ll join the Production.Product table to the Production.ProductInventory table with a left join so I can list all the products(including those without any inventory) and their corresponding quantities.</p>
<p>SELECT&#160;&#160;&#160;&#160; p.Name as ProductName,    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; inv.Quantity     <br />FROM Production.Product p     <br />LEFT JOIN Production.ProductInventory inv     <br />&#160;&#160;&#160; ON p.ProductID = inv.ProductId </p>
<p>But after reviewing the output, I realize that the location name is needed to make this query complete, so I’ll add the location table to the query with an inner join:</p>
<p>SELECT&#160;&#160;&#160;&#160; p.Name as ProductName,    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; inv.Quantity     <br />FROM Production.Product p     <br />LEFT JOIN Production.ProductInventory inv     <br />&#160;&#160;&#160; ON p.ProductID = inv.ProductId     <br />INNER JOIN Production.Location l     <br />&#160;&#160;&#160; ON l.LocationID = inv.LocationID     <br />ORDER BY p.Name desc</p>
<p>But now something is wrong with the code, because the result set is missing the products without inventory.&#160; Why?</p>
<p>That’s because using an inner join to add the location table filters out the products with no quantity.&#160; Since they have no inventory, they do not have a row in the ProductInventory table and hence nothing to join to in the ON l.LocationID = inv.LocationID clause.&#160; Since I want to keep the rows where inv.Quantity is null, let’s change this to a left join:</p>
<p>SELECT&#160;&#160;&#160;&#160; p.Name as ProductName,    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; inv.Quantity     <br />FROM Production.Product p     <br />LEFT JOIN Production.ProductInventory inv     <br />&#160;&#160;&#160; ON p.ProductID = inv.ProductId     <br />LEFT JOIN Production.Location l     <br />&#160;&#160;&#160; ON l.LocationID = inv.LocationID     </p>
<p>And that works!&#160; All of our products (even if they do not have any inventory) are in the result set.</p>
<p><strong>WHERE clause vs. ON clause</strong></p>
<p>The WHERE clause is typically used to restrict the results of a query.&#160; But in the case of an outer join, using the WHERE clause can give you the wrong results.&#160; Here I want to see all the products and the total quantity of each product currently in work.&#160; So I left join the Production.Product table to the Production.WorkOrder table to see all 504 products and the quantity in work.&#160; Quantity is zero for products not currently in production.</p>
<p>SELECT&#160;&#160;&#160; p.Name,    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; COUNT(wo.WorkOrderID)     <br />FROM Production.Product p     <br />LEFT JOIN Production.WorkOrder wo     <br />&#160;&#160;&#160; ON p.productID = wo.ProductID     <br />GROUP BY p.Name </p>
<p>But I don’t want to see all work orders, just the most recent ones.&#160; So I try to limit the query to the most recent work orders by putting the StartDate in the WHERE clause:</p>
<p>SELECT&#160;&#160;&#160; p.Name,    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; COUNT(wo.WorkOrderID)     <br />FROM Production.Product p     <br />LEFT JOIN Production.WorkOrder wo     <br />&#160;&#160;&#160; ON p.productID = wo.ProductID     <br />WHERE wo.StartDate &gt;= &#8217;1/1/2004&#8242;     <br />GROUP BY p.Name </p>
<p>But now I have lost my products not currently in production.&#160; So now what?&#160; I’ll move the StartDate restriction to the ON clause, so it will be part of the join:</p>
<p>SELECT&#160;&#160;&#160; p.name,    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; COUNT(wo.WorkOrderID)     <br />FROM Production.Product p     <br />LEFT JOIN Production.WorkOrder wo     <br />&#160;&#160;&#160; ON p.productID = wo.ProductID     <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; AND StartDate &gt;= &#8217;1/1/2004&#8242;     <br />GROUP BY p.Name</p>
<p>Now I will return all 504 products, with the quantities for the most recent work orders.&#160; So why does using the ON clause work and not the WHERE clause?&#160; There are two reasons.&#160; First the ON clause is applied as part of the join and the WHERE clause is applied after the join.&#160; Secondly, the WHERE clause is applied to the right side of the left outer join, the WorkOrder table, the table we only want rows from if there is a match.</p>
<p>So, don’t be afraid to use an outer join, just be aware of the gotcha’s when coding a left/right join.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dianemcnurlan.com/2010/04/the-two-things-you-need-to-know-about-outer-joins/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL to get all Month End and Begin Dates</title>
		<link>http://www.dianemcnurlan.com/2010/03/sql-to-get-all-month-end-and-begin-dates/</link>
		<comments>http://www.dianemcnurlan.com/2010/03/sql-to-get-all-month-end-and-begin-dates/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 06:15:12 +0000</pubDate>
		<dc:creator>Diane McNurlan</dc:creator>
				<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://www.dianemcnurlan.com/?p=104</guid>
		<description><![CDATA[Many web sites and blogs will tell you how to find the last day, first day of a month or year But what if you need the month end and begin dates for a specific time period?  Well, here is the code for that: &#8211;script to get month begining &#38; end dates for a time...]]></description>
			<content:encoded><![CDATA[<p>Many web sites and blogs will tell you how to find the last day, first day of a month or year</p>
<p>But what if you need the month end and begin dates for a specific time period?  Well, here is the code for that:</p>
<p>&#8211;script to get month begining &amp; end dates for a time period<br />
&#8211;declare all variables<br />
DECLARE @StartDate datetime<br />
DECLARE @EndDate datetime<br />
DECLARE @MonthEndDate datetime<br />
DECLARE @MonthBeginDate datetime</p>
<p>DECLARE @MonthlyDates Table<br />
(    MonthID INT NOT NULL IDENTITY(1,1),<br />
MonthBeginDate SMALLDATETIME NOT NULL,<br />
MonthEndDate SMALLDATETIME NOT NULL<br />
)</p>
<p>&#8211;set the time period here<br />
SET @StartDate = &#8217;3/1/2009&#8242;<br />
SET @EndDate = &#8217;5/31/2012&#8242;</p>
<p>&#8211;Get the first month&#8217;s begin and end dates<br />
SELECT @MonthBeginDate = DATEADD(dd,-(DAY(@StartDate)-1),@StartDate)<br />
SELECT @MonthEndDate = DATEADD(mm,1,@StartDate) &#8211; DAY(DATEADD(mm,1,@StartDate))</p>
<p>&#8211;do the first insert into the holding table<br />
INSERT INTO @MonthlyDates<br />
(MonthBeginDate, MonthEndDate)<br />
VALUES<br />
(@MonthBeginDate, @MonthEndDate)</p>
<p>&#8211;use while loop to move through each month<br />
WHILE @MonthEndDate &lt; @EndDate<br />
BEGIN</p>
<p>SELECT @MonthBeginDate = DATEADD(mm, 1, @MonthBeginDate)<br />
SELECT @MonthEndDate = DATEADD(dd, -1, DATEADD(mm, 1, @MonthBeginDate))</p>
<p>INSERT INTO @MonthlyDates<br />
(MonthBeginDate, MonthEndDate)<br />
VALUES<br />
(@MonthBeginDate, @MonthEndDate)</p>
<p>END<br />
SELECT<br />
MonthBeginDate,<br />
MonthEndDate<br />
FROM @MonthlyDates</p>
<p>So this code will give you all the months begin &amp; end dates, in order.  Now in this code I&#8217;m not looking at when the @StartDate or @EndDate falls in the month.  For example, if I pass into the code a start date of March 10, 2009 it will return, as the first row, the begin and end dates for the month of March.  If you wanted to only return dates for whole months that your range covers (in the above example that would be a start month of April), you would need to alter the code.</p>
<p>Oh, and it is good for leap years too!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dianemcnurlan.com/2010/03/sql-to-get-all-month-end-and-begin-dates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Good reference links for the TOP Keyword</title>
		<link>http://www.dianemcnurlan.com/2010/02/good-reference-links-for-the-top-keyword/</link>
		<comments>http://www.dianemcnurlan.com/2010/02/good-reference-links-for-the-top-keyword/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 03:26:02 +0000</pubDate>
		<dc:creator>Diane McNurlan</dc:creator>
				<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://www.dianemcnurlan.com/2010/02/good-reference-links-for-the-top-keyword/</guid>
		<description><![CDATA[This past week I needed to use the TOP keyword for some code and came across some excellent resources: First, the quick basics of top: Dynamically controlling the number of rows affected by a SQL Server query Next, a good article on how to retrieve top and bottom rows together: How to Retrieve TOP and...]]></description>
			<content:encoded><![CDATA[<p>This past week I needed to use the TOP keyword for some code and came across some excellent resources:</p>
<p>First, the quick basics of top:</p>
<p><a href="http://www.mssqltips.com/tip.asp?tip=1535">Dynamically controlling the number of rows affected by a SQL Server query</a></p>
<p>Next, a good article on how to retrieve top and bottom rows together:</p>
<p><a href="http://blog.sqlauthority.com/2008/03/02/sql-server-how-to-retrieve-top-and-bottom-rows-together-using-t-sql/">How to Retrieve TOP and BOTTOM Rows Together using T-SQL</a></p>
<p>And an excellent article on the TOP per group scenario:</p>
<p><a href="http://sqlblog.com/blogs/adam_machanic/archive/2008/02/08/who-s-on-first-solving-the-top-per-group-problem-part-1-technique.aspx">Who&#8217;s On First? Solving the Top per Group Problem</a></p>
<p>And the book <a href="http://oreilly.com/catalog/9780735626034/#product-details">Inside Microsoft SQL Server 2008 T-SQL Querying</a> there is a whole chapter mostly on TOP; Chapter 9 TOP and APPLY.</p>
<p>TOP isn’t something used everyday in SQL Server, but when you need it, you’ll be happy it’s part of TSQL.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dianemcnurlan.com/2010/02/good-reference-links-for-the-top-keyword/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The New Date &amp; Time Datatypes are great, but&#8230;</title>
		<link>http://www.dianemcnurlan.com/2009/09/the-new-date-time-datatypes-are-great-but/</link>
		<comments>http://www.dianemcnurlan.com/2009/09/the-new-date-time-datatypes-are-great-but/#comments</comments>
		<pubDate>Sun, 06 Sep 2009 11:51:00 +0000</pubDate>
		<dc:creator>Diane McNurlan</dc:creator>
				<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://www.dianemcnurlan.com/2009/09/the-new-date-time-datatypes-are-great-but</guid>
		<description><![CDATA[The first time I read about the new Date and Time datatypes I though “Well, that’s nice”.&#160; But the more I think about it the happier I am.&#160; No more stripping off the time values to do a date only comparison.&#160; Thank goodness.&#160;&#160; Some other pluses;&#160; possible use of indexes, safe to use BETWEEN for...]]></description>
			<content:encoded><![CDATA[<p>The first time I read about the new Date and Time datatypes I though “Well, that’s nice”.&#160; But the more I think about it the happier I am.&#160; No more stripping off the time values to do a date only comparison.&#160; Thank goodness.&#160;&#160; Some other pluses;&#160; possible use of indexes, safe to use BETWEEN for date ranges, easier reading of code without all of those CONVERT functions.&#160; </p>
<p>But don’t be so eager to leave out the time part.&#160; You need to be absolutely sure that you don’t need the time piece.&#160; If your not sure, keep the time part in a column separate from the date.</p>
<p>There is some good sample data for these datatypes in the AdventureWorks2008 database.&#160; Take a look at the Human Resources.Employee table, Birthdates &amp; Hire Date columns.&#160; And also look at Human Resources.Shift table, Start Time &amp; End Time columns.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dianemcnurlan.com/2009/09/the-new-date-time-datatypes-are-great-but/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Linker Servers and Server Aliases</title>
		<link>http://www.dianemcnurlan.com/2009/03/linker-server-server-alias-%e2%80%9cfun%e2%80%9d/</link>
		<comments>http://www.dianemcnurlan.com/2009/03/linker-server-server-alias-%e2%80%9cfun%e2%80%9d/#comments</comments>
		<pubDate>Sun, 15 Mar 2009 20:50:45 +0000</pubDate>
		<dc:creator>Diane McNurlan</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://www.dianemcnurlan.com/2006/12/linker-server-server-alias-%e2%80%9cfun%e2%80%9d</guid>
		<description><![CDATA[Just the other day I received a call from a developer with a database problem. He was receiving timeouts when he called a particular stored procedure from his application. So I took a look at the proc, reviewed the code, and tried to run it. It just ran and ran and ran, no error messages,...]]></description>
			<content:encoded><![CDATA[<p>Just the other day I received a call from a developer with a database problem. He was receiving timeouts when he called a particular stored procedure from his application.  So I took a look at the proc, reviewed the code, and tried to run it.  It just ran and ran and ran, no error messages, nothing.  Then I tried to recompile the proc, same thing, just hung.  So I stopped it, looked at the amount of data it needed to run, not much data involved, so I cut the proc into pieces and ran it a chuck at a time.  Finally, I got to the problem part of the code, the part that just hung.  In reading the code, I noticed that it was referencing a linked server, hmmm, where does this point to?  So, I go into the Client Network Utility and here we are, an old server that no longer exists!  Change the server name and port number and yes! The proc complies and runs!  Weird, wonder why it just didn&#8217;t just return an error message. Oh well, all in a day&#8217;s fun!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dianemcnurlan.com/2009/03/linker-server-server-alias-%e2%80%9cfun%e2%80%9d/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adventures in SQL Server Performance Tuning &#8211; Joins vs. Where Exists</title>
		<link>http://www.dianemcnurlan.com/2008/03/more-adventures-in-sql-server-performance-tuning-joins-vs-where-exists/</link>
		<comments>http://www.dianemcnurlan.com/2008/03/more-adventures-in-sql-server-performance-tuning-joins-vs-where-exists/#comments</comments>
		<pubDate>Mon, 10 Mar 2008 00:08:31 +0000</pubDate>
		<dc:creator>Diane McNurlan</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://www.dianemcnurlan.com/2008/02/more-adventures-in-sql-server-performance-tuning-joins-vs-where-exists</guid>
		<description><![CDATA[What is wrong with this query? SELECT c.CustomerName, b.BillingID FROM BillingInfo bi JOIN Customer c ON bi.CustomerID = c.CustomerID JOIN DailyTransactions dt ON bi.BillingID = dt.BillingID WHERE dt.Transdate &#62;= @startdate AND dt.Transdate &#60; @enddate Well, the first thing that I see is that we are joining to the DailyTransactions table, but we aren&#8217;t returning any...]]></description>
			<content:encoded><![CDATA[<p>What is wrong with this query?</p>
<p>SELECT c.CustomerName, b.BillingID<br />
FROM BillingInfo bi<br />
JOIN Customer c<br />
ON bi.CustomerID = c.CustomerID<br />
JOIN DailyTransactions dt<br />
ON bi.BillingID = dt.BillingID<br />
WHERE dt.Transdate &gt;= @startdate<br />
AND dt.Transdate &lt; @enddate</p>
<p>Well, the first thing that I see is that we are joining to the DailyTransactions table, but we aren&#8217;t returning<br />
any columns in the results set.  Why?  The reason is because the goal of this query is to return all customers<br />
that have transactions in a given period, so we must check the DailyTransations table for this.  But we don&#8217;t care<br />
if the customer had 1 transaction or 1000, nor do we need any columns of data from that table, so here is better<br />
(quicker!) way to do this:</p>
<p>SELECT c.CustomerName, b.BillingID<br />
FROM BillingInfo bi<br />
JOIN Customer c<br />
ON bi.CustomerID = c.CustomerID<br />
WHERE EXISTS (SELECT 1 FROM DailyTransactions dt<br />
WHERE bi.BillingID = dt.BillingID<br />
AND    Transdate &gt;= @startdate<br />
AND    Transdate &lt; @enddate)</p>
<p>A WHERE EXISTS will be much faster than a join because as soon as the first match is found for that BillingID,<br />
SQL Server stops looking for more, unlike a join, which will match up every row.</p>
<p>When I fixed a stored procedure with this exact problem, I cut the run time required by two-thirds.  Since this stored<br />
procedure loads a dropdown in Reporting Services, that cut the time required to load the report.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dianemcnurlan.com/2008/03/more-adventures-in-sql-server-performance-tuning-joins-vs-where-exists/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A Very Simple PIVOT Example</title>
		<link>http://www.dianemcnurlan.com/2007/07/a-very-simple-pivot-example/</link>
		<comments>http://www.dianemcnurlan.com/2007/07/a-very-simple-pivot-example/#comments</comments>
		<pubDate>Sun, 15 Jul 2007 03:46:27 +0000</pubDate>
		<dc:creator>Diane McNurlan</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://www.dianemcnurlan.com/2007/01/a-very-simple-pivot-example</guid>
		<description><![CDATA[When I first started working with the new PIVOT command in SQL Server 2005, it didn&#8217;t make any sense to me.  So I created some very simple examples on my own to help with my understanding.  Here is one.  First, I create the CTE (as I explained in my last post): WITH Sales as (...]]></description>
			<content:encoded><![CDATA[<p>When I first started working with the new PIVOT command in SQL Server 2005, it didn&#8217;t make any sense to me.  So I created some very simple examples on my own to help with my understanding.  Here is one.  First, I create the CTE (as I explained in my last post):</p>
<p>WITH Sales as (<br />
SELECT  SalesOrderID, Name, OrderDate<br />
FROM Sales.SalesTerritory st<br />
INNER JOIN Sales.SalesOrderHeader soh<br />
ON st.TerritoryID = soh.TerritoryID<br />
WHERE OrderDate &gt;= &#8217;7/1/2001&#8242;<br />
AND OrderDate &lt; &#8217;8/1/2001&#8242;<br />
)</p>
<p>The CTE contains the sales orders and the territory name for that sale during the month of July 2001.  Next we will create the PIVOT.  The goal of the PIVOT is to count the number of sales by territory.  Not very exciting, but a good simple example:</p>
<p>SELECT Convert(varchar(20), OrderDate, 101) AS &#8216;Sales Date&#8217;,<br />
Northwest,<br />
Central,<br />
Southwest,<br />
Canada,<br />
France,<br />
Germany,<br />
Australia<br />
FROM sales  &#8212; the CTE above<br />
PIVOT<br />
(<br />
COUNT (SalesOrderID)<br />
FOR Name in ([Northwest], [Central], [Southwest], [Canada], [France], [Germany], [Australia])) as a<br />
ORDER BY OrderDate</p>
<p>One downside to the PIVOT command is you need to know the column names at design time.  They must be hard coded.  The only way you can get around this is to use dynamic SQL.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dianemcnurlan.com/2007/07/a-very-simple-pivot-example/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A little bit about Common Table Expressions</title>
		<link>http://www.dianemcnurlan.com/2007/06/a-little-bit-about-common-table-expressions/</link>
		<comments>http://www.dianemcnurlan.com/2007/06/a-little-bit-about-common-table-expressions/#comments</comments>
		<pubDate>Sat, 02 Jun 2007 05:22:41 +0000</pubDate>
		<dc:creator>Diane McNurlan</dc:creator>
				<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://www.dianemcnurlan.com/2007/01/a-little-bit-about-common-table-expressions</guid>
		<description><![CDATA[I was planning to do a series of blogs about the new PIVOT and UNPIVOT functionality in SQL Server 2005, but I&#8217;ve decided to take a step back and do a post on Common Table Expressions (CTE&#8217;s) first. They are used in conjunction with PIVOT and UNPIVOT to make the code a bit cleaner. If...]]></description>
			<content:encoded><![CDATA[<p class="MsoNormal">I was planning to do a series of blogs about the new PIVOT and UNPIVOT functionality in SQL Server 2005, but I&#8217;ve decided to take a step back and do a post on Common Table Expressions (CTE&#8217;s) first.  They are used in conjunction with PIVOT and UNPIVOT to make the code a bit cleaner.</p>
<p>If you have used derived tables in your scripts before than Common Table Expressions will easy for you to understand.<br />
Here is a simple derived table example (from the Adventure Works sample DB) that returns the total quantity of items for each order in the month of December 2001:</p>
<p>SELECT  SalesOrderID,<br />
NumberOfItems<br />
FROM(</p>
<div style="margin-left: 40px">SELECT      soh.SalesOrderID,<br />
Sum(sod.OrderQty) as NumberOfItems<br />
FROM Sales.SalesOrderHeader soh<br />
INNER JOIN Sales.SalesOrderDetail sod<br />
ON soh.SalesOrderID = sod.SalesOrderID<br />
WHERE OrderDate &gt;= &#8217;12/1/2001&#8242;<br />
AND OrderDate &lt; &#8217;1/1/2002&#8242;<br />
GROUP BY soh.SalesOrderID</div>
<p>) AS TotalQty</p>
<p>And here is the same query, done as a CTE.  Notice the use of the WITH keyword:<br />
WITH TotalQty<br />
AS (</p>
<div style="margin-left: 40px">SELECT   soh.SalesOrderID,<br />
SUM(sod.OrderQty) as NumberOfItems<br />
FROM Sales.SalesOrderHeader soh<br />
INNER JOIN Sales.SalesOrderDetail sod<br />
ON soh.SalesOrderID = sod.SalesOrderID<br />
WHERE OrderDate &gt;= &#8217;12/1/2001&#8242;<br />
AND OrderDate &lt; &#8217;1/1/2002&#8242;<br />
GROUP BY soh.SalesOrderID</div>
<p>)</p>
<p>SELECT SalesOrderID,<br />
NumberOfItems<br />
FROM TotalQty</p>
<p class="MsoNormal">
<p><!--[if !supportLineBreakNewLine]--></p>
<p><!--[endif]--></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dianemcnurlan.com/2007/06/a-little-bit-about-common-table-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Is that Column Really a Varchar?</title>
		<link>http://www.dianemcnurlan.com/2007/01/is-that-column-really-a-varchar/</link>
		<comments>http://www.dianemcnurlan.com/2007/01/is-that-column-really-a-varchar/#comments</comments>
		<pubDate>Wed, 31 Jan 2007 04:56:59 +0000</pubDate>
		<dc:creator>Diane McNurlan</dc:creator>
				<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://www.dianemcnurlan.com/2007/01/is-that-column-really-a-varchar</guid>
		<description><![CDATA[If the data is padded with trailing zeros, well than it might as well be a char datatype. I&#8217;ve been working with a series of partitioned tables this past week that are just huge, well over 170 million rows total and over 100 columns. As I was writing some queries for the data I discovered...]]></description>
			<content:encoded><![CDATA[<p class="MsoNormal">If the data is padded with trailing zeros, well than it might as well be a char datatype.</p>
<p class="MsoNormal">I&#8217;ve been working with a series of partitioned tables this past week that are just huge, well over 170 million rows total and over 100 columns. As I was writing some queries for the data I discovered that all of the varchar data was stored with trailing spaces up to the length of the column.  When the data was loaded into the tables, it wasn&#8217;t stripped of the trailing spaces.     So, if a column was defined as a varchar (30) and held a piece of data such as &#8220;Tom&#8221;, it took all 30 bytes not just 3.  Of course this made the tables very large.  I created a clean up script using the trim functions to strip the trailing spaces from the data.</p>
<p>My tables are much smaller now and faster too!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dianemcnurlan.com/2007/01/is-that-column-really-a-varchar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

