<?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>Eric Fickes &#187; tsql</title>
	<atom:link href="http://ericfickes.com/category/sql/tsql-sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://ericfickes.com</link>
	<description>Design minded Internet Programmer</description>
	<lastBuildDate>Fri, 28 Oct 2011 04:14:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>An aggregate may not appear in the set list of an UPDATE statement</title>
		<link>http://ericfickes.com/2011/02/an-aggregate-may-not-appear-in-the-set-list-of-an-update-statement/</link>
		<comments>http://ericfickes.com/2011/02/an-aggregate-may-not-appear-in-the-set-list-of-an-update-statement/#comments</comments>
		<pubDate>Mon, 21 Feb 2011 06:43:00 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[internets]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[tsql]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1998</guid>
		<description><![CDATA[Ever seen the error &#8220;An aggregate may not appear in the set list of an UPDATE statement&#8221; when working with SQL Server?  I ran into this one recently after trying to put a COUNT in an UPDATE statement.  I was rewriting &#8230; <a href="http://ericfickes.com/2011/02/an-aggregate-may-not-appear-in-the-set-list-of-an-update-statement/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Ever seen the error &#8220;An aggregate may not appear in the set list of an UPDATE statement&#8221; when working with SQL Server?  I ran into this one recently after trying to put a COUNT in an UPDATE statement.  I was rewriting some legacy code to use a stored procedure, and it turned out to be the perfect case for a <a title="Read about Temporary Tables on MSDN" href="http://msdn.microsoft.com/en-us/library/ms177399.aspx" target="_blank">Temporary Table</a>.</p>
<p>Instead of boring you with a work scenario, let&#8217;s take a simpler one that uses the <a title="Download Microsoft's AdventureWorks database from this site so you can play along at home" href="http://msftdbprodsamples.codeplex.com/releases/view/37109" target="_blank">AdventureWorks</a> database.  This example will create a list of sales people, total order count for each person, and store this list a single table variable to be used as the final data table.</p>
<p>Should be three simple steps right?</p>
<h2>1. Create @Table variable</h2>
<pre class="brush: sql; title: ; notranslate">
DECLARE @SalesPeople TABLE
(
  EmployeeID int NOT NULL,
  SalesPersonID int NOT NULL,
  FullName varchar(200) NOT NULL,
  Title varchar(200) NOT NULL,
  sales_count int NULL default 0
)
</pre>
<h2>2. INSERT sales people into @Table</h2>
<pre class="brush: sql; title: ; notranslate">
-- HACKISH : Match SalesPersonID to EmployeeID, and fill @SalesPeople
INSERT INTO @SalesPeople
( EmployeeID, SalesPersonID, FullName, Title )
SELECT	e.EmployeeID, sp.SalesPersonID,
		c.FirstName + ' ' + c.LastName as FullName,
		e.Title
FROM	Sales.SalesPerson sp,
		HumanResources.Employee e,
		Person.Contact c
WHERE	sp.SalesPersonID = e.EmployeeID
AND		e.ContactID = c.ContactID
</pre>
<h2>3. UPDATE @Table with COUNT</h2>
<pre class="brush: sql; title: ; notranslate">
UPDATE	@SalesPeople
SET
	sales_count = COUNT( soh.SalesOrderID )
FROM	@SalesPeople sp, Sales.SalesOrderHeader soh
WHERE EXISTS (
	SELECT DISTINCT SalesPersonID FROM @SalesPeople WHERE SalesPersonID = soh.SalesPersonID
)
AND	sp.SalesPersonID = soh.SalesPersonID
</pre>
<div id="attachment_2004" class="wp-caption alignnone" style="width: 775px"><a style="font-weight: normal;" href="http://ericfickes.com/wp-content/uploads/2011/02/aggregate-error.png" rel="lightbox[1998]"><img title="aggregate-error" src="http://ericfickes.com/wp-content/uploads/2011/02/aggregate-error.png" alt="" width="765" height="187" /></a><p class="wp-caption-text">Not COUNT allowed in an UPDATE SET statement</p></div>
<p>The third step is where the original error comes in, so let&#8217;s update this to four steps and see how a Table Variable gets through this.</p>
<h2>1 &amp; 2 &#8211; Repeat from above</h2>
<h2>3. Create Table Variable of order counts</h2>
<pre class="brush: sql; title: ; notranslate">
SELECT	soh.SalesPersonID, COUNT( soh.SalesOrderID ) AS sales_count
INTO	#SalesOrderCounts
FROM	Sales.SalesOrderHeader soh
WHERE EXISTS (
	SELECT DISTINCT SalesPersonID FROM @SalesPeople WHERE SalesPersonID = soh.SalesPersonID
)
GROUP BY soh.SalesPersonID
</pre>
<h2>4. Update @Table with order counts</h2>
<pre class="brush: sql; title: ; notranslate">
UPDATE	@SalesPeople
SET		sales_count = tmp.sales_count
FROM	@SalesPeople sp, #SalesOrderCounts tmp
WHERE	sp.SalesPersonID = tmp.SalesPersonID
</pre>
<p>And here&#8217;s the full script from start to finish with the table variable in use.</p>
<pre class="brush: sql; title: ; notranslate">
-- Master table of sales people
DECLARE @SalesPeople TABLE
(
  EmployeeID int NOT NULL,
  SalesPersonID int NOT NULL,
  FullName varchar(200) NOT NULL,
  Title varchar(200) NOT NULL,
  sales_count int NULL default 0
)

-- Match SalesPersonID to EmployeeID, and fill @SalesPeople
INSERT INTO @SalesPeople
( EmployeeID, SalesPersonID, FullName, Title )
SELECT	e.EmployeeID, sp.SalesPersonID,
		c.FirstName + ' ' + c.LastName as FullName,
		e.Title
FROM	Sales.SalesPerson sp, HumanResources.Employee e, Person.Contact c
WHERE	sp.SalesPersonID = e.EmployeeID
AND		e.ContactID = c.ContactID

-- put sales counts into the other kind of #tableVariable
SELECT	soh.SalesPersonID, COUNT( soh.SalesOrderID ) AS sales_count
INTO	#SalesOrderCounts
FROM	Sales.SalesOrderHeader soh
WHERE EXISTS (
	SELECT DISTINCT SalesPersonID FROM @SalesPeople WHERE SalesPersonID = soh.SalesPersonID
)
GROUP BY soh.SalesPersonID

-- Update our master @table with data from #tableVariable
UPDATE	@SalesPeople
SET		sales_count = tmp.sales_count
FROM	@SalesPeople sp, #SalesOrderCounts tmp
WHERE	sp.SalesPersonID = tmp.SalesPersonID

-- dump the results
SELECT	FullName, Title, sales_count
FROM	@SalesPeople

-- cleanup
drop table #SalesOrderCounts
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2011/02/an-aggregate-may-not-appear-in-the-set-list-of-an-update-statement/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Use sys.dm_exec_sessions to disconnect SQL user connections</title>
		<link>http://ericfickes.com/2011/01/use-sys-dm_exec_sessions-to-disconnect-sql-user-connections/</link>
		<comments>http://ericfickes.com/2011/01/use-sys-dm_exec_sessions-to-disconnect-sql-user-connections/#comments</comments>
		<pubDate>Tue, 04 Jan 2011 03:18:00 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[internets]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tsql]]></category>

		<guid isPermaLink="false">http://ericfickes.posterous.com/use-sysdmexecsessions-to-disconnect-sql-user</guid>
		<description><![CDATA[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 -- init vars DECLARE &#8230; <a href="http://ericfickes.com/2011/01/use-sys-dm_exec_sessions-to-disconnect-sql-user-connections/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><!--[CDATA[</p>
<div class="data type-sql"-->
<table cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<pre class="line_numbers"><span id="L1">1</span>
<span id="L2">2</span>
<span id="L3">3</span>
<span id="L4">4</span>
<span id="L5">5</span>
<span id="L6">6</span>
<span id="L7">7</span>
<span id="L8">8</span>
<span id="L9">9</span>
<span id="L10">10</span>
<span id="L11">11</span>
<span id="L12">12</span>
<span id="L13">13</span>
<span id="L14">14</span>
<span id="L15">15</span>
<span id="L16">16</span>
<span id="L17">17</span>
<span id="L18">18</span>
<span id="L19">19</span>
<span id="L20">20</span>
<span id="L21">21</span>
<span id="L22">22</span>
<span id="L23">23</span>
<span id="L24">24</span>
<span id="L25">25</span>
<span id="L26">26</span>
<span id="L27">27</span>
<span id="L28">28</span>
<span id="L29">29</span>
<span id="L30">30</span>
<span id="L31">31</span>
<span id="L32">32</span>
<span id="L33">33</span>
<span id="L34">34</span>
<span id="L35">35</span>
<span id="L36">36</span></pre>
</td>
<td width="100%">
<div class="highlight">
<pre>
<div id="LC1" class="line"><span class="c1">-- init vars</span></div>
<div id="LC2" class="line"><span class="k">DECLARE</span> <span class="o">@</span><span class="n">sessID</span> <span class="nb">int</span><span class="p">,</span></div>
<div id="LC3" class="line">		<span class="o">@</span><span class="n">dbName</span> <span class="nb">varchar</span><span class="p">(</span><span class="mi">50</span><span class="p">),</span></div>
<div id="LC4" class="line">		<span class="o">@</span><span class="n">userName</span> <span class="nb">varchar</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span></div>
<div id="LC6" class="line"><span class="k">SET</span> <span class="o">@</span><span class="n">dbName</span>	<span class="o">=</span> <span class="s1">'DA413'</span>	<span class="c1">-- your database name</span></div>
<div id="LC7" class="line"><span class="k">SET</span> <span class="o">@</span><span class="n">userName</span>	<span class="o">=</span> <span class="s1">'DA413'</span>	<span class="c1">-- sql user account to look for</span></div>
<div id="LC10" class="line"><span class="c1">-- use a cursor to store all session_ids</span></div>
<div id="LC11" class="line"><span class="k">DECLARE</span> <span class="n">session_cursor</span> <span class="k">CURSOR</span></div>
<div id="LC12" class="line"><span class="k">FOR</span></div>
<div id="LC13" class="line">	<span class="k">SELECT</span>	<span class="n">session_id</span></div>
<div id="LC14" class="line">	<span class="k">FROM</span>	<span class="n">sys</span><span class="p">.</span><span class="n">dm_exec_sessions</span></div>
<div id="LC15" class="line">	<span class="k">WHERE</span>	<span class="n">original_login_name</span> <span class="o">=</span> <span class="o">@</span><span class="n">userName</span></div>
<div id="LC17" class="line">	<span class="c1">-- open cursor and grab first row</span></div>
<div id="LC18" class="line">	<span class="k">OPEN</span> <span class="n">session_cursor</span></div>
<div id="LC19" class="line">	<span class="k">FETCH</span> <span class="k">NEXT</span> <span class="k">FROM</span> <span class="n">session_cursor</span> <span class="k">INTO</span> <span class="o">@</span><span class="n">sessID</span></div>
<div id="LC21" class="line">	<span class="c1">-- loop through session_ids</span></div>
<div id="LC22" class="line">	<span class="n">WHILE</span> <span class="o">@@</span><span class="n">FETCH_STATUS</span> <span class="o">=</span> <span class="mi">0</span></div>
<div id="LC23" class="line">	<span class="k">BEGIN</span></div>
<div id="LC25" class="line">		<span class="c1">-- kill it</span></div>
<div id="LC26" class="line">		<span class="c1">-- using EXEC because the sproc kill does not like @variables</span></div>
<div id="LC27" class="line">		<span class="k">EXEC</span><span class="p">(</span><span class="s1">'kill '</span> <span class="o">+</span> <span class="o">@</span><span class="n">sessID</span><span class="p">)</span></div>
<div id="LC29" class="line">		<span class="c1">-- get the next session_id</span></div>
<div id="LC30" class="line">		<span class="k">FETCH</span> <span class="k">NEXT</span> <span class="k">FROM</span> <span class="n">session_cursor</span> <span class="k">INTO</span> <span class="o">@</span><span class="n">sessID</span></div>
<div id="LC31" class="line">	<span class="k">END</span></div>
<div id="LC33" class="line"><span class="c1">-- cursor cleanup</span></div>
<div id="LC34" class="line"><span class="k">CLOSE</span> <span class="n">session_cursor</span></div>
<div id="LC35" class="line"><span class="k">DEALLOCATE</span> <span class="n">session_cursor</span></div>
</pre>
</div>
</td>
</tr>
</tbody>
</table>
<p><a href="http://ericfickes.posterous.com/use-sysdmexecsessions-to-disconnect-sql-user">Permalink</a></p>
<p>| <a href="http://ericfickes.posterous.com/use-sysdmexecsessions-to-disconnect-sql-user#comment">Leave a comment</a></p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2011/01/use-sys-dm_exec_sessions-to-disconnect-sql-user-connections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>2 of 10,388 days remaining #TRON</title>
		<link>http://ericfickes.com/2010/12/2-of-10388-days-remaining-tron/</link>
		<comments>http://ericfickes.com/2010/12/2-of-10388-days-remaining-tron/#comments</comments>
		<pubDate>Wed, 15 Dec 2010 18:38:36 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[fun]]></category>
		<category><![CDATA[internets]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[motivation]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tsql]]></category>

		<guid isPermaLink="false">http://ericfickes.posterous.com/2-of-10388-days-remaining-tron</guid>
		<description><![CDATA[&#8211; Using tsql to figure out how long until TRON:LEGACY DECLARE @tron datetime, @tron_legacy datetime SET @tron = &#8217;7/9/1982 12:00:00&#8242; SET @tron_legacy = &#8217;12/17/2010 12:00:00&#8242; SELECT CAST( DATEDIFF( DD, GETDATE(), @tron_legacy ) as varchar(2) ) + &#8216; of&#8217; + CAST &#8230; <a href="http://ericfickes.com/2010/12/2-of-10388-days-remaining-tron/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><!--[CDATA[</p>
<div-->&#8211; Using tsql to figure out how long until TRON:LEGACY</p>
<div>DECLARE @tron datetime,</div>
<div><span> </span>@tron_legacy datetime</div>
<div>SET @tron = &#8217;7/9/1982 12:00:00&#8242;</div>
<div>SET @tron_legacy = &#8217;12/17/2010 12:00:00&#8242;</div>
<div>SELECT<span> </span>CAST( DATEDIFF( DD, GETDATE(), @tron_legacy ) as varchar(2) ) + &#8216; of&#8217; + CAST ( DATEDIFF( DD, @tron, @tron_legacy ) AS VARCHAR(1000) ) + &#8216; days remaining&#8217; as &#8216;How long until TRON:LEGACY?&#8217;</div>
<div>&#8211; returns</div>
<div>&#8211; 2 of10388 days remaining</div>
<p><a href="http://ericfickes.posterous.com/2-of-10388-days-remaining-tron">Permalink</a></p>
<p>| <a href="http://ericfickes.posterous.com/2-of-10388-days-remaining-tron#comment">Leave a comment</a></p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/12/2-of-10388-days-remaining-tron/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>TSQL : How to find all database tables ending with an UPPERCASE X</title>
		<link>http://ericfickes.com/2010/12/tsql-how-to-find-all-database-tables-ending-with-an-uppercase-x/</link>
		<comments>http://ericfickes.com/2010/12/tsql-how-to-find-all-database-tables-ending-with-an-uppercase-x/#comments</comments>
		<pubDate>Wed, 08 Dec 2010 20:28:59 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[internets]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[tsql]]></category>

		<guid isPermaLink="false">http://ericfickes.posterous.com/tsql-how-to-find-all-database-tables-ending-w</guid>
		<description><![CDATA[1 2 3 4 5 6 7 8 9 10 -- Give me all tables ending with an UPPERCASE X SELECT table_name, SUBSTRING( table_name, LEN(table_name), 1 ) as &#39;end&#39; FROM INFORMATION_SCHEMA.TABLES -- SELECT ascii(&#39;X&#39;) = 88 -- SELECT ascii(&#39;x&#39;) = &#8230; <a href="http://ericfickes.com/2010/12/tsql-how-to-find-all-database-tables-ending-with-an-uppercase-x/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><![CDATA[
<div class="data type-sql">
<table cellspacing="0" cellpadding="0">
<tr>
<td>
<pre class="line_numbers"><span rel="#L1" id="L1">1</span>
<span rel="#L2" id="L2">2</span>
<span rel="#L3" id="L3">3</span>
<span rel="#L4" id="L4">4</span>
<span rel="#L5" id="L5">5</span>
<span rel="#L6" id="L6">6</span>
<span rel="#L7" id="L7">7</span>
<span rel="#L8" id="L8">8</span>
<span rel="#L9" id="L9">9</span>
<span rel="#L10" id="L10">10</span>
</pre>
</td>
<td width="100%">
<div class="highlight">
<pre />
<div class="line" id="LC1"><span class="c1">-- Give me all tables ending with an UPPERCASE X</span></div>
<div class="line" id="LC2"></div>
<div class="line" id="LC3"><span class="k">SELECT</span>	<span class="k">table_name</span><span class="p">,</span> <span class="k">SUBSTRING</span><span class="p">(</span> <span class="k">table_name</span><span class="p">,</span> <span class="n">LEN</span><span class="p">(</span><span class="k">table_name</span><span class="p">),</span> <span class="mi">1</span> <span class="p">)</span> <span class="k">as</span> <span class="s1">&#39;end&#39;</span></div>
<div class="line" id="LC4"></div>
<div class="line" id="LC5"><span class="k">FROM</span>	<span class="n">INFORMATION_SCHEMA</span><span class="p">.</span><span class="n">TABLES</span></div>
<div class="line" id="LC6"></div>
<div class="line" id="LC7"><span class="c1">-- SELECT ascii(&#39;X&#39;) = 88</span></div>
<div class="line" id="LC8"><span class="c1">-- SELECT ascii(&#39;x&#39;) = 120</span></div>
<div class="line" id="LC9"><span class="k">WHERE</span>	<span class="n">ASCII</span><span class="p">(</span> <span class="k">SUBSTRING</span><span class="p">(</span> <span class="k">table_name</span><span class="p">,</span> <span class="n">LEN</span><span class="p">(</span><span class="k">table_name</span><span class="p">),</span> <span class="mi">1</span> <span class="p">)</span> <span class="p">)</span> <span class="o">=</span> <span class="mi">88</span></div>
<div class="line" id="LC10"></div>
</pre>
</div>
</td>
</tr>
</table></div>
</p>
<p><a href="http://ericfickes.posterous.com/tsql-how-to-find-all-database-tables-ending-w">Permalink</a> </p>
<p>	| <a href="http://ericfickes.posterous.com/tsql-how-to-find-all-database-tables-ending-w#comment">Leave a comment</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/12/tsql-how-to-find-all-database-tables-ending-with-an-uppercase-x/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Selecting random ids using TOP and a CTE</title>
		<link>http://ericfickes.com/2010/09/selecting-random-ids-using-top-and-a-cte/</link>
		<comments>http://ericfickes.com/2010/09/selecting-random-ids-using-top-and-a-cte/#comments</comments>
		<pubDate>Thu, 30 Sep 2010 05:43:49 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[common table expression]]></category>
		<category><![CDATA[cte]]></category>
		<category><![CDATA[mssqlserver]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[SQLSERVER]]></category>
		<category><![CDATA[top]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1675</guid>
		<description><![CDATA[While testing visualizations in a Flex application, I needed to do some underlying data cleanup in SQL Server.  One of my tasks was to manually update an entity table and set the status column to one of three possibilities.  Status &#8230; <a href="http://ericfickes.com/2010/09/selecting-random-ids-using-top-and-a-cte/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>While testing visualizations in a Flex application, I needed to do some underlying data cleanup in SQL Server.  One of my tasks was to manually update an entity table and set the status column to one of three possibilities.  Status group A and B both needed to be roughly 20% of my tables total record count, and status group C would be the remaining rows that weren&#8217;t touched by status A or status B.  Oh and there&#8217;s one more thing, the ids in each status group can not be in sequential order, they have to be random.</p>
<p>At first I thought no sweat.  My dataset is still small ( only 2000 rows ), so if we want uber control I could do the math and generate my id lists by hand.  Yes, hand crafting is possible and under a deadline that kind of logic almost makes sense.  However, I already know the table I&#8217;m working with will grow in the future, and I&#8217;ll probably have to do this data update again, so why not do this right?  While playing around with different select statements I had a &#8220;EUREKA!&#8221; moment.  <a title="TSQL's TOP operator on MSDN" href="http://msdn.microsoft.com/en-us/library/ms189463.aspx" target="_blank">SQL Server&#8217;s TOP operator</a> supports PERCENT, not just number.  I couldn&#8217;t believe it.  I use TOP at least once a week and I always forget about TOP PERCENT.  Since I already know how to select random rows via <a title="SQL Server's Common Table Expressions are super helpful" href="http://msdn.microsoft.com/en-us/library/ms190766.aspx" target="_blank">CTE</a>, it  was time to put it all together.</p>
<p>Before giving you the final SQL, here are the important parts to be familiar with.  Also, for the sake of example I&#8217;m using the <a title="Download the AdventureWorks database from Codeplex" href="http://msftdbprodsamples.codeplex.com/releases/view/37109" target="_blank">AdventureWorks database</a> so you can play along at home.</p>
<h2><a title="MSSQL's TOP operator on MSDN" href="http://msdn.microsoft.com/en-us/library/ms189463.aspx" target="_blank">TOP PERCENT</a></h2>
<p>If you just need 50% of the rows in a table, but you&#8217;re not concerned about the sequence returned, you can fire this query.  This will give you a sequential listing of ProductIDs</p>
<pre class="brush: sql; title: ; notranslate">
SELECT TOP 50 PERCENT ProductID
FROM Production.Product
ORDER BY ProductID
</pre>
<p>Which will look something like this.</p>
<p><a href="http://ericfickes.com/wp-content/uploads/2010/09/SELECT-TOP-20-PERCENT.png" rel="lightbox[1675]"><img class="aligncenter size-full wp-image-1682" title="SELECT TOP 20 PERCENT" src="http://ericfickes.com/wp-content/uploads/2010/09/SELECT-TOP-20-PERCENT.png" alt="SQL's TOP operator returns rows sequentially" width="274" height="255" /></a></p>
<h2><a title="A Common Table Expression can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query..." href="http://msdn.microsoft.com/en-us/library/ms190766.aspx" target="_blank">COMMON TABLE EXPRESSION</a></h2>
<p>Now let&#8217;s say you want to randomly pull all rows from a table.  This can be achieved using this CTE.</p>
<pre class="brush: sql; title: ; notranslate">
WITH data( ProductID ) AS (
	SELECT	ProductID
	FROM	Production.Product
)
SELECT	ProductID
FROM	data
ORDER BY NEWID()
</pre>
<p>Which will look like this</p>
<p><a href="http://ericfickes.com/wp-content/uploads/2010/09/SELECT-RANDOM-CTE.png" rel="lightbox[1675]"><img class="aligncenter size-full wp-image-1689" title="SELECT RANDOM DATA using CTE" src="http://ericfickes.com/wp-content/uploads/2010/09/SELECT-RANDOM-CTE.png" alt="Common Table Expressions in SQLSERVER are super helpful" width="271" height="381" /></a></p>
<p>If you&#8217;re looking to <a title="Select random value from preset list - tSQL, CTE" href="http://ericfickes.posterous.com/tsql-select-a-random-value-using-cte" target="_blank">randomly select values from a pre-determined list, see my CTE sample here</a>.</p>
<p>So now that you&#8217;ve seen TOP PERCENT and CTE in action, it&#8217;s time to put these together and solve my initial task of creating randomly selected groups of ids, of a percent size.</p>
<p>RANDOMLY SELECT TOP PERCENT</p>
<p>Putting it all together, here is the query I used to create my first status group.</p>
<pre class="brush: sql; title: ; notranslate">
WITH data( ProductID ) AS (
	SELECT	ProductID
	FROM	Production.Product
)
SELECT TOP 20 PERCENT ProductID
FROM	data
ORDER BY NEWID()
</pre>
<p>Which gives me a dataset that is 20% of all rows in Production.Product, and the ids are in random order.</p>
<p>And there you have it.  Randomly selecting a percent sized data set from a table in SQL Server.  The SQL here is really pretty simple, but for some reason I always forget TOP PERCENT.  I&#8217;m hoping this post will help me remember TOP PERCENT, and maybe even help somebody else with some TSQL.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/09/selecting-random-ids-using-top-and-a-cte/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What if you want to PIVOT against a text column?</title>
		<link>http://ericfickes.com/2010/04/what-if-you-want-to-pivot-against-a-text-column/</link>
		<comments>http://ericfickes.com/2010/04/what-if-you-want-to-pivot-against-a-text-column/#comments</comments>
		<pubDate>Sat, 01 May 2010 05:04:27 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[coalesce]]></category>
		<category><![CDATA[dynamic sql]]></category>
		<category><![CDATA[exec]]></category>
		<category><![CDATA[pivot]]></category>
		<category><![CDATA[quotename]]></category>
		<category><![CDATA[SQLSERVER]]></category>
		<category><![CDATA[table variable]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1435</guid>
		<description><![CDATA[If you&#8217;ve ever worked with or researched SQL Server&#8217;s PIVOT function, you probably noticed most of the samples pivot against an id column.  Typically an int column like EmployeeID, or StoreID.  That&#8217;s fine and dandy, but what happens when you &#8230; <a href="http://ericfickes.com/2010/04/what-if-you-want-to-pivot-against-a-text-column/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve ever worked with or researched SQL Server&#8217;s <a title="Using PIVOT and UNPIVOT functions" href="http://msdn.microsoft.com/en-us/library/ms177410.aspx" target="_blank">PIVOT function</a>, you probably noticed most of the samples pivot against an id column.  Typically an int column like EmployeeID, or StoreID.  That&#8217;s fine and dandy, but what happens when you want to PIVOT against a varchar column?  If you&#8217;ve been in this need you know this is a bit of a task.</p>
<p>I had this need on an app recently and built a little dynamic sql action that does just this.  The example below however, uses the the <a title="DatabaseLog table in the AdventureWorks DB" href="http://msdn.microsoft.com/en-us/library/ms124872.aspx" target="_blank">DatabaseLog</a> table in the <a title="Download AdventureWorks sample databases for free" href="http://msdn.microsoft.com/en-us/library/ms124501(v=SQL.100).aspx" target="_blank">AdventureWorks sample database</a> to return a count of Events logged for each Schema.  Before jumping into the PIVOT, here&#8217;s a simple query that gives you the same information, all Schemas, Events, and Event counts.</p>
<pre class="brush: sql; title: ; notranslate">
SELECT      [Schema], [Event], COUNT( [Event] ) AS 'event_count'
FROM        DatabaseLog
GROUP BY    [Schema], [Event]
ORDER BY    [Schema]
</pre>
<p>Running this query should give you a long result looking something like this.</p>
<p><a href="http://ericfickes.com/wp-content/uploads/2010/04/regular_count_query.png" rel="lightbox[1435]"><img class="aligncenter size-full wp-image-1442" title="Regular COUNT query" src="http://ericfickes.com/wp-content/uploads/2010/04/regular_count_query.png" alt="Data is there, format isn't nice like PIVOT" width="409" height="394" /></a></p>
<p>While this query returns the same information to you, I don&#8217;t like this format as much as using PIVOT.  This query result is long and requires a bit of manipulation to get into a readable format.</p>
<p>Now let&#8217;s have a look at retrieving the same information using the PIVOT function.</p>
<pre class="brush: sql; title: ; notranslate">
/*
Example of a dynamic PIVOT against a varchar column from the Adventureworks database

References :
PIVOT &amp; UNPIVOT function

http://msdn.microsoft.com/en-us/library/ms177410.aspx

AdventureWorks sample Databases

http://msdn.microsoft.com/en-us/library/ms124501(v=SQL.100).aspx

AdventreWorks.DatabaseLog

http://msdn.microsoft.com/en-us/library/ms124872.aspx

*/

USE AdventureWorks

-- populate temp Event table
SELECT DISTINCT [Event] as 'Event'
INTO	#events
FROM	DatabaseLog

-- this var will hold a comma delimited list of [Event]
DECLARE	@eventList nvarchar(max)

-- create a flattened [Event], list for the PIVOT statement
SELECT	@eventList = COALESCE( @eventList + ', ', '') + CAST( QUOTENAME( [Event] ) AS VARCHAR(1000) )
FROM	#events
ORDER BY [Event]

-- drop table var since our data now lives in @eventList
DROP TABLE #events

-- this var will hold the dynamic PIVOT sql
DECLARE @pvt_sql nvarchar(max)

-- NOTE : we're using dynamic sql here because PIVOT
-- does not support sub SELECT in the 'FOR Event IN ( )'
-- part of the query.
-- If we don't use dynamic SQL here, the PIVOT function
-- requires you to hard code each 'Event'
-- Using SELECT * here so the [Event] columns are auto included
SET @pvt_sql = 'SELECT	*
                FROM
                (
                    SELECT	[Event], [Schema]
                    FROM	DatabaseLog
                ) AS data
                PIVOT
                (
                    COUNT( Event )
                    FOR Event IN
                    ( ' + @eventList + ' )
                ) AS pvt'

-- run the query
EXEC sp_executesql @pvt_sql
</pre>
<p>Assuming you have the AdventureWorks database installed on your server, running this sql should give you a result looking something like this.</p>
<div id="attachment_1439" class="wp-caption aligncenter" style="width: 597px"><a href="http://ericfickes.com/wp-content/uploads/2010/04/dynamic_pivot_dblog.png" rel="lightbox[1435]"><img class="size-full wp-image-1439" title="Schema Event counts" src="http://ericfickes.com/wp-content/uploads/2010/04/dynamic_pivot_dblog.png" alt="Dynamic PIVOT on text column Event" width="587" height="143" /></a><p class="wp-caption-text">Show all Schemas and count of each Event type</p></div>
<p>This query result was truncated to fit in this post, but just know the query above creates a column for every Event in the Databaselog table.</p>
<p>A quick explanation of what&#8217;s happening in this sql</p>
<ol>
<li>First you fill a table variable ( #events ) with all Events from DatabaseLog</li>
<li>Next create a comma delimited list of the Events inside of the table variable</li>
<li>Drop the table variable now that we&#8217;ve got our delimited list of Events</li>
<li>Build the PIVOT statement as a string so you can inject the Events list</li>
<li>Fire the dynamic SQL via EXEC</li>
</ol>
<p>Dynamic SQL is something that comes in handy from time to time, but I do my best to only use it if I absolutely have to.  In this case we&#8217;re using it because the PIVOT function does not allow sub SELECT statements.  This is also why we create a specially formatted delimited list of Events prior to building the dynamic sql.</p>
<p>So there you have it, one example of using PIVOT against a varchar column instead of an integer column.  Also, this is a pretty good example of a dynamic PIVOT since it&#8217;s pretty simple.  I hope this makes sense, and if you have any suggestions of better techniques, I&#8217;d love to hear it.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/04/what-if-you-want-to-pivot-against-a-text-column/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Incorrect syntax near the keyword &#8216;table&#8217; in TSQL</title>
		<link>http://ericfickes.com/2010/04/incorrect-syntax-near-the-keyword-table-in-tsql/</link>
		<comments>http://ericfickes.com/2010/04/incorrect-syntax-near-the-keyword-table-in-tsql/#comments</comments>
		<pubDate>Wed, 07 Apr 2010 22:18:21 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[#table]]></category>
		<category><![CDATA[DECLARE]]></category>
		<category><![CDATA[SQLSERVER]]></category>
		<category><![CDATA[SQLSERVER 2005]]></category>
		<category><![CDATA[table variable]]></category>

		<guid isPermaLink="false">http://ericfickes.com/2010/04/incorrect-syntax-near-the-keyword-table-in-tsql/</guid>
		<description><![CDATA[Ran into something little that I know I&#8217;m going to forget if I don&#8217;t write down. It appears that when using a TABLE variable in tsql ( SQL Server 2005 ), you must DECLARE that variable on it&#8217;s own line, &#8230; <a href="http://ericfickes.com/2010/04/incorrect-syntax-near-the-keyword-table-in-tsql/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Ran into something little that I know I&#8217;m going to forget if I don&#8217;t write down.  It appears that when using a TABLE variable in tsql ( SQL Server 2005 ), you must DECLARE that variable on it&#8217;s own line, as opposed to inline with your other @variables.</p>
<p>Typically in my sprocs or sql scripts I do my best to have a main DECLARE block and seperate my @variables with a comma like this.</p>
<div id="attachment_1412" class="wp-caption aligncenter" style="width: 378px"><a href="http://ericfickes.com/wp-content/uploads/2010/04/declare-bad.png" rel="lightbox[1414]"><img class="size-full wp-image-1412" title="Incorrect syntax near the keyword 'table'" src="http://ericfickes.com/wp-content/uploads/2010/04/declare-bad.png" alt="Typically I DECLARE=" width="368" height="125" /></a><p class="wp-caption-text">If you&#39;re using a TABLE variable, put it on it&#39;s own DECLARE line</p></div>
<p>After some mucking around, it turns out moving the TABLE @variable to it&#8217;s own DECLARE line fixes this issue.</p>
<div id="attachment_1413" class="wp-caption aligncenter" style="width: 304px"><a href="http://ericfickes.com/wp-content/uploads/2010/04/declare-good.png" rel="lightbox[1414]"><img class="size-full wp-image-1413" title="DECLARE TABLE @variables on their own line" src="http://ericfickes.com/wp-content/uploads/2010/04/declare-good.png" alt="DECLARE TABLE @variables on their own line" width="294" height="106" /></a><p class="wp-caption-text">DECLARE TABLE @variables on their own line</p></div>
<p>I haven&#8217;t found this info in SQL BOL, so I hope this helps somebody else.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/04/incorrect-syntax-near-the-keyword-table-in-tsql/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How to TWEET from a SQL CLR Stored Procedure</title>
		<link>http://ericfickes.com/2010/03/how-to-tweet-from-a-sql-crl-stored-procedure/</link>
		<comments>http://ericfickes.com/2010/03/how-to-tweet-from-a-sql-crl-stored-procedure/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 01:10:58 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[.net assembly]]></category>
		<category><![CDATA[.net Common Language Runtime]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[CLR SPROC]]></category>
		<category><![CDATA[sproc]]></category>
		<category><![CDATA[sql server 2005]]></category>
		<category><![CDATA[stored procedure]]></category>
		<category><![CDATA[tweet]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1133</guid>
		<description><![CDATA[Here&#8217;s another SQL Server 2005 geek out moment, a CLR SPROC that tweets to Twitter. Big shoutout to Danny Battison for sharing the C# code to post to Twitter. This is what got me started on the C# side of &#8230; <a href="http://ericfickes.com/2010/03/how-to-tweet-from-a-sql-crl-stored-procedure/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s another SQL Server 2005 geek out moment, a CLR SPROC that tweets to Twitter.  Big shoutout to <a title="Danny Battison is a C# rocker!" href="http://www.dreamincode.net/code/snippet2556.htm" target="_blank">Danny Battison for sharing the C# code to post to Twitter</a>.  This is what got me started on the C# side of things.  Also, you can skip all my ramblings here and just <a title="CLR SPROC &gt; Tweetsproc sample code" href="http://ericfickes.com/code/tweetsproc.zip" target="_blank">download code here</a> and fire it up.  The zip file contains all the source code, the compiled assembly file, and install.sql that shows you how to hook this up.</p>
<p>Being the SQL junky that I am, I was interested in trying out SQL Server&#8217;s new  <a title="CLR Stored Procedures on MSDN" href="http://msdn.microsoft.com/en-us/library/ms131094.aspx" target="_blank">CLR Stored Procedures</a>.  A CLR sproc is a stored procedure that is able to use .net code that you&#8217;ve compiled into an assembly file.  For you classic ASP heads out there, think of the ASP page being the sproc, and the .net assembly being your COM object ( cringe, let&#8217;s talk about classic ASP ).  While there are plenty of great articles on <a title="Writing CLR Stored Procedures on SQLTEAM.com" href="http://www.sqlteam.com/article/writing-clr-stored-procedures-in-charp-introduction-to-charp-part-1" target="_blank">writing CLR stored procedures</a>, I&#8217;m going to breeze through the code that makes up this project.</p>
<h2>First make a .net class library that will be compiled into an assembly file.</h2>
<pre class="brush: csharp; title: ; notranslate">
using System;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

/// &lt;summary&gt;
/// This assembly will be used by a SQL2005 SPROC to communicate
/// with twitter.com
/// &lt;/summary&gt;
public sealed class tweetsproc
{
    /*
     * TWITTER CODE BORROWED FROM :
     *  http://www.dreamincode.net/code/snippet2556.htm
     *
     * A function to post an update to Twitter programmatically
     * Author: Danny Battison
     * Contact: gabehabe@hotmail.com
     */

    /// &lt;summary&gt;
    /// Post an update to a Twitter acount
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;username&quot;&gt;The username of the account&lt;/param&gt;
    /// &lt;param name=&quot;password&quot;&gt;The password of the account&lt;/param&gt;
    /// &lt;param name=&quot;tweet&quot;&gt;The status to post&lt;/param&gt;
    [Microsoft.SqlServer.Server.SqlProcedure(Name = &quot;PostTweet&quot;)]
    //public static void PostTweet( string username, string password, string tweet)
    public static void PostTweet(   SqlString username,
                                    SqlString password,
                                    SqlString tweet)
    {
        try
        {
            // encode the username/password
            string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username.ToString() + &quot;:&quot; + password.ToString()));
            // determine what we want to upload as a status
            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(&quot;status=&quot; + tweet.ToString());

            // Create a WebPermission.
            WebPermission myWebPermission1 = new WebPermission();

            // Allow Connect access to the specified URLs.
            myWebPermission1.AddPermission(NetworkAccess.Connect,new Regex(&quot;http://www\\.twitter\\.com/.*&quot;,
              RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline));

            myWebPermission1.Demand();

            // connect with the update page
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(&quot;http://twitter.com/statuses/update.xml&quot;);

            // set the method to POST
            request.Method = &quot;POST&quot;;
            request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change!
            // set the authorisation levels
            request.Headers.Add(&quot;Authorization&quot;, &quot;Basic &quot; + user);
            request.ContentType = &quot;application/x-www-form-urlencoded&quot;;
            // set the length of the content
            request.ContentLength = bytes.Length;

            // set up the stream
            Stream reqStream = request.GetRequestStream();
            // write to the stream
            reqStream.Write(bytes, 0, bytes.Length);
            // close the stream
            reqStream.Close();

            // Let's get the Response from Twitter
            var webresp = request.GetResponse();
            // Let's read the Response
            var sread = new StreamReader( webresp.GetResponseStream() );

            // Use SqlContext to return data to the QueryAnalyzer results window
            SqlContext.Pipe.Send( sread.ReadToEnd() );

        }
        catch (Exception exc)
        {
            // send error back
            SqlContext.Pipe.Send(exc.Message);
        }
    }
}
</pre>
<h3>Here&#8217;s the app.config for this assembly.</h3>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;configuration&gt;
  &lt;system.web&gt;
    &lt;trust level=&quot;Full&quot; processRequestInApplicationTrust=&quot;true&quot; originUrl=&quot;&quot; /&gt;
  &lt;/system.web&gt;
&lt;/configuration&gt;
</pre>
<p>Once you build this project, you should have your assembly ( tweetsproc.dll ) which will be used by your CLR Sproc.  Now it&#8217;s time to do some SQL server work.</p>
<h2>Enable CLR access for SQL server</h2>
<pre class="brush: sql; title: ; notranslate">
EXEC sp_configure @configname = 'clr enabled', @configvalue = 1
RECONFIGURE WITH OVERRIDE
GO
</pre>
<h2>Create the SQL Assembly</h2>
<pre class="brush: sql; title: ; notranslate">
CREATE ASSEMBLY tweetsproc_clr_assembly from 'C:\Users\eric\Desktop\blog\tweetsproc.dll'
WITH PERMISSION_SET = EXTERNAL_ACCESS
GO
</pre>
<h2>Create your SPROC</h2>
<pre class="brush: sql; title: ; notranslate">
CREATE PROC tweetsproc_tweet(	@username as nvarchar(50),
								@password as nvarchar(50),
								@tweet as nvarchar(140)
							)
AS
	-- [Assembly Name].[Class Name].[CLR function Name]
	EXTERNAL NAME tweetsproc_clr_assembly.tweetsproc.PostTweet
GO
</pre>
<h2>Tweet from a sproc</h2>
<pre class="brush: sql; title: ; notranslate">EXEC tweetsproc_tweet 'TwitterUsername', 'TwitterPassword', 'Hey @ericfickes, I''m tweeting from my database too!'</pre>
<p>Running this sproc returns the XML response from Twitter.</p>
<div id="attachment_1142" class="wp-caption aligncenter" style="width: 678px"><a href="http://ericfickes.com/wp-content/uploads/2010/03/tweetsproc_tweet-response1.png" rel="lightbox[1133]"><img class="size-full wp-image-1142" title="Twitter response from tweet sproc" src="http://ericfickes.com/wp-content/uploads/2010/03/tweetsproc_tweet-response1.png" alt="Twitter response from tweet sproc" width="668" height="719" /></a><p class="wp-caption-text">Tweetsproc returns the full Twitter response</p></div>
<p>That&#8217;s one sample CLR SPROC in the bank!  Feel free to download this code and try it out yourself.  I&#8217;d love to get some feedback on anybody looking to use this for real.  While tweeting from a stored procedure probably isn&#8217;t a hot topic for anybody, this is a nice teaser for what you can do with CLR sprocs now.</p>
<p><a title="CLR SPROC &gt; Tweetsproc sample code" href="http://ericfickes.com/code/tweetsproc.zip" target="_blank">Download code here.</a></p>
<p>Inside this zip you&#8217;ll find this.</p>
<ul>
<li>install.sql is everything you need to install this on your database</li>
<li>tweetsproc.dll is the twitter assembly used by the sproc</li>
<li>tweetsproc folder is the .net class library project</li>
</ul>
<div id="attachment_1139" class="wp-caption aligncenter" style="width: 289px"><a href="http://ericfickes.com/wp-content/uploads/2010/03/tweetsproczip.png" rel="lightbox[1133]"><img class="size-full wp-image-1139" title="Contents of tweetsproc.zip" src="http://ericfickes.com/wp-content/uploads/2010/03/tweetsproczip.png" alt="Contents of tweetsproc.zip" width="279" height="114" /></a><p class="wp-caption-text">Everything you need to get TWEETING from a sproc</p></div>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/03/how-to-tweet-from-a-sql-crl-stored-procedure/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Does SQL Server Management Studio truncate your results?</title>
		<link>http://ericfickes.com/2010/02/does-sql-server-management-studio-truncate-your-results/</link>
		<comments>http://ericfickes.com/2010/02/does-sql-server-management-studio-truncate-your-results/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 17:52:28 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[column size]]></category>
		<category><![CDATA[max characters]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[results to text]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[sql server management studio]]></category>
		<category><![CDATA[truncated results]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1103</guid>
		<description><![CDATA[Ever work with query results that are so long SQL Server Management Studio truncates the results? I ran into this issue recently while running some utility sprocs that generate C# code for me.  I was thinking I&#8217;d have to refactor &#8230; <a href="http://ericfickes.com/2010/02/does-sql-server-management-studio-truncate-your-results/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Ever work with query results that are so long SQL Server Management Studio truncates the results?</p>
<div id="attachment_1104" class="wp-caption aligncenter" style="width: 567px"><a href="http://ericfickes.com/wp-content/uploads/2010/02/1.truncated-result.png" rel="lightbox[1103]"><img class="size-full wp-image-1104" title="Results to text are truncated" src="http://ericfickes.com/wp-content/uploads/2010/02/1.truncated-result.png" alt="truncated query results" width="557" height="408" /></a><p class="wp-caption-text">sproc results are truncated</p></div>
<p>I ran into this issue recently while running some utility sprocs that generate C# code for me.  I was thinking I&#8217;d have to refactor my sprocs, but then I found this helpful setting under Query Options.</p>
<div id="attachment_1107" class="wp-caption aligncenter" style="width: 673px"><a href="http://ericfickes.com/wp-content/uploads/2010/02/2.qry-max-char1.png" rel="lightbox[1103]"><img class="size-full wp-image-1107" title="Query Options Dialog" src="http://ericfickes.com/wp-content/uploads/2010/02/2.qry-max-char1.png" alt="This is the Query Options dialog" width="663" height="401" /></a><p class="wp-caption-text">Update Max.num characters per column in Query Options &gt; Results &gt; Text</p></div>
<p>This solved my problem and will hopefully solve yours as well.</p>
<ol>
<li>Right click the query editor</li>
<li>Left click &#8220;Query Options&#8230;&#8221;</li>
<li>Expand Results in the tree on the left ( in popup dialog )</li>
<li>Click on Text under Results</li>
<li>Set &#8220;Maximum number of characters displayed in each column&#8221; to a number large enough to see all your results.</li>
</ol>
<p>Quick and easy, hope I remember this setting.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/02/does-sql-server-management-studio-truncate-your-results/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What happens in EXEC, stays in EXEC. Lifespan of a MSSQL table variable</title>
		<link>http://ericfickes.com/2010/02/using-mssql-table-variables-with-exec-statements/</link>
		<comments>http://ericfickes.com/2010/02/using-mssql-table-variables-with-exec-statements/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 19:44:49 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[exec]]></category>
		<category><![CDATA[mssql]]></category>
		<category><![CDATA[mssql2000]]></category>
		<category><![CDATA[mssql2005]]></category>
		<category><![CDATA[scope]]></category>
		<category><![CDATA[SELECT INTO]]></category>
		<category><![CDATA[table variable]]></category>
		<category><![CDATA[temp table]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1080</guid>
		<description><![CDATA[One of my all time favorite features of MSSQL 2005+ is being able to create table variables on the fly from SELECT statements. This isn&#8217;t a lesson in what table variables are, but here is an easy sample in case &#8230; <a href="http://ericfickes.com/2010/02/using-mssql-table-variables-with-exec-statements/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;">One of my all time favorite features of MSSQL 2005+ is being able to create table variables on the fly from SELECT statements.  This isn&#8217;t a lesson in what table variables are, but here is an easy sample in case this is a new concept.</p>
<p style="text-align: left;">Running this query</p>
<pre class="brush: sql; title: ; notranslate">SELECT * INTO #myTableVar FROM YourTable</pre>
<p>Gives you a new table variable named myTableVar.  Table variables are scoped to the active connection, so running this will work.</p>
<pre class="brush: sql; title: ; notranslate">
// make table var
SELECT * INTO #myTableVar FROM YourTable
// show me the data
SELECT * FROM #myTableVar
// you can drop it if you wish
DROP TABLE #myTableVar
</pre>
<p>However, let&#8217;s say you have an aspx page or a sproc that runs this query.</p>
<pre class="brush: sql; title: ; notranslate">SELECT * INTO #myTableVar FROM YourTable</pre>
<p>You can not access myTableVar in a separate connection to the database because as soon as the first query&#8217;s connection closes, myTableVar gets dropped.     Here are a few other scenarios that also demonstrate the scoping of a table variable.</p>
<pre class="brush: sql; title: ; notranslate">
-- FAILS
EXEC ('SELECT * INTO #tmp FROM MyTable;');
-- #tmp does not exist
SELECT * FROM #tmp
</pre>
<div id="attachment_1084" class="wp-caption aligncenter" style="width: 404px"><a href="http://ericfickes.com/wp-content/uploads/2010/02/exec1-no-tmp-table.png" rel="lightbox[1080]"><img class="size-full wp-image-1084      " title="Table variable lives inside of EXEC" src="http://ericfickes.com/wp-content/uploads/2010/02/exec1-no-tmp-table.png" alt="#tmp only exists inside of EXEC" width="394" height="179" /></a><p class="wp-caption-text">Table variable #tmp lives inside of EXEC</p></div>
<p>Here we see that the table variable #tmp only lives for the life of the statement inside of EXEC.  The second SELECT * calls is outside of the EXEC statement.</p>
<pre class="brush: sql; title: ; notranslate">
-- #tmp2 works inside of EXEC statement
EXEC ('SELECT * INTO #tmp2 FROM MyTable; SELECT * FROM #tmp2');
</pre>
<div id="attachment_1086" class="wp-caption aligncenter" style="width: 570px"><a href="http://ericfickes.com/wp-content/uploads/2010/02/exec2-tmp-inside-exec.png" rel="lightbox[1080]"><img class="size-full wp-image-1086   " title="tmp2 lives inside of EXEC" src="http://ericfickes.com/wp-content/uploads/2010/02/exec2-tmp-inside-exec.png" alt="table variables in EXEC live in EXEC" width="560" height="111" /></a><p class="wp-caption-text">What happens in EXEC, stays in EXEC</p></div>
<p>Here #tmp2 works because it&#8217;s being used inside of the EXEC statement.  This is worth knowing if you work with dynamic sql statements and exec.</p>
<pre class="brush: sql; title: ; notranslate">
-- works!
SELECT * INTO #tmp FROM MyTable;
-- #tmp exists
SELECT * FROM #tmp
</pre>
<div id="attachment_1087" class="wp-caption aligncenter" style="width: 318px"><a href="http://ericfickes.com/wp-content/uploads/2010/02/exec3-normal-tmp-exists.png" rel="lightbox[1080]"><img class="size-full wp-image-1087" title="typical sample of using mssql table variable" src="http://ericfickes.com/wp-content/uploads/2010/02/exec3-normal-tmp-exists.png" alt="typical sample of using mssql table variable" width="308" height="153" /></a><p class="wp-caption-text">typical sample of using mssql table variable</p></div>
<p>This is a typical example that you may use inside a sproc, trigger, script, etc.  Both sql calls live in the same space, so #tmp exists.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/02/using-mssql-table-variables-with-exec-statements/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

