<?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; sql</title>
	<atom:link href="http://ericfickes.com/category/sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://ericfickes.com</link>
	<description>Internets, Databases, Skateboards, Ice Hockeys, and Family</description>
	<lastBuildDate>Thu, 22 Jul 2010 22:45:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Use SQL to insert a label in front of a DataBound list</title>
		<link>http://ericfickes.com/2010/06/use-sql-to-insert-a-label-in-front-of-a-databound-list/</link>
		<comments>http://ericfickes.com/2010/06/use-sql-to-insert-a-label-in-front-of-a-databound-list/#comments</comments>
		<pubDate>Thu, 10 Jun 2010 02:35:27 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[combobox]]></category>
		<category><![CDATA[DataBind]]></category>
		<category><![CDATA[DataBound]]></category>
		<category><![CDATA[union]]></category>
		<category><![CDATA[viewstate]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1473</guid>
		<description><![CDATA[Here&#8217;s a clever little solution I would like to add to the book of &#8216;get it done&#8217;.  While this particular example uses ASP.NET controls, this concept really applies to any language that supports DataBinding to a control. The base concept is using your knowledge of SQL&#8217;s UNION operator to add a temp value to the [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a clever little solution I would like to add to the book of &#8216;get it done&#8217;.  While this particular example uses ASP.NET controls, this concept really applies to any language that supports DataBinding to a control.</p>
<p>The base concept is using your knowledge of SQL&#8217;s UNION operator to add a temp value to the beginning of a list of data from a sql query.  In the past I&#8217;ve done this countless times via code, and recently I didn&#8217;t have the time to do this, so I updated the query to a UNION, and I was good to go.</p>
<p>Now I&#8217;m not selling this as a &#8216;best practice&#8217;, but I do consider this one more reason why it&#8217;s good to know SQL.</p>
<p><strong>Problem</strong> : Using a SQLDataSource to populate a DropDown component, how do you inject a spacer value in position 0?  EX : &#8220;- select value -&#8221;</p>
<p><strong>Solution</strong> : Inject your spacer value in your SelectCommand via sql&#8217;s UNION operator</p>
<h3>ComboBox</h3>
<pre class="brush: csharp;">
&lt;asp:DropDownList runat=&quot;server&quot; ID=&quot;meter_manufacturer_dd&quot; DataSourceID=&quot;sql_meterManufacturer&quot; DataTextField=&quot;Manufacturer&quot; /&gt;
</pre>
<h2>DataSource</h2>
<pre class="brush: sql;">
&lt;asp:SqlDataSource runat=&quot;server&quot; ID=&quot;sql_meterManufacturer&quot;
    SelectCommand=&quot;
    SELECT '- Choose Manufacturer -' as Manufacturer
    UNION
    SELECT DISTINCT Manufacturer FROM Smart_Meter_DEF&quot;
    /&gt;</pre>
<p>What this solution gets you.</p>
<p>1. Your spacer value shows up in position 0 ( because the first character is &#8211; and not alphanumeric )</p>
<p style="text-align: center;"><a href="http://ericfickes.com/wp-content/uploads/2010/06/dropdown1.png" rel="lightbox[1473]"><img class="size-full wp-image-1474 aligncenter" title="DataBound ComboBox with spacer injected via SQL" src="http://ericfickes.com/wp-content/uploads/2010/06/dropdown1.png" alt="SQL is your friend" width="187" height="180" /></a></p>
<p style="text-align: center;">2. Auto ViewState caching ( EG : going straight .NET solution, .NET handles persisting your dropdown selection between postbacks )</p>
<p style="text-align: center;"><a href="http://ericfickes.com/wp-content/uploads/2010/06/dropdown2.png" rel="lightbox[1473]"><img class="size-full wp-image-1475 aligncenter" title="DataBound ComboBox retains selection between Postbacks" src="http://ericfickes.com/wp-content/uploads/2010/06/dropdown2.png" alt="Injecting a value via SQL eliminates need for custom ViewState handling" width="189" height="185" /></a></p>
<p>* in this sample, the connectionString for the SqlDataSource is set in code.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/06/use-sql-to-insert-a-label-in-front-of-a-databound-list/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 want to PIVOT against a varchar column?  If you&#8217;ve been in this need you know [...]]]></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;">
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;">
/*
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>0</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, as opposed to inline with your other @variables. Typically in my sprocs or sql scripts [...]]]></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>0</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 things.  Also, you can skip all my ramblings here and just download code here and [...]]]></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;">
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;">
&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;">
EXEC sp_configure @configname = 'clr enabled', @configvalue = 1
RECONFIGURE WITH OVERRIDE
GO
</pre>
<h2>Create the SQL Assembly</h2>
<pre class="brush: sql;">
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;">
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;">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 my sprocs, but then I found this helpful setting under Query Options. This solved my [...]]]></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[random]]></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 this is a new concept. Running this query SELECT * INTO #myTableVar FROM YourTable Gives [...]]]></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;">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;">
// 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;">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;">
-- 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;">
-- #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;">
-- 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>
		<item>
		<title>How to JOIN two tables using LINQ to SQL</title>
		<link>http://ericfickes.com/2010/02/how-to-join-two-tables-using-linq-to-sql/</link>
		<comments>http://ericfickes.com/2010/02/how-to-join-two-tables-using-linq-to-sql/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 01:27:53 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[join]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[linq to sql]]></category>
		<category><![CDATA[linqtosql]]></category>
		<category><![CDATA[query]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1065</guid>
		<description><![CDATA[Wanted to share this since it gave me so much trouble figuring out.  It&#8217;s a simple SQL query ported to LINQ to SQL that joins two tables to return a filtered listed of data. Here are the tables from my schema Here is a basic SQL statement I could fire to retrieve my user videos. [...]]]></description>
			<content:encoded><![CDATA[<p>Wanted to share this since it gave me so much trouble figuring out.  It&#8217;s a simple SQL query ported to LINQ to SQL that joins two tables to return a filtered listed of data.</p>
<p>Here are the tables from my schema<br />
<a href="http://ericfickes.com/wp-content/uploads/2010/02/user-user_videos-video.png" rel="lightbox[1065]"><img class="aligncenter size-full wp-image-1068" title="My three user tables" src="http://ericfickes.com/wp-content/uploads/2010/02/user-user_videos-video.png" alt="user, user_video, video tables" width="465" height="317" /></a></p>
<p>Here is a basic SQL statement I could fire to retrieve my user videos.</p>
<pre class="brush: sql;">
select  *
from    video v, user_videos uv
where   v.vid = uv.vid
and     uv.uid = 2
</pre>
<p><a href="http://ericfickes.com/wp-content/uploads/2010/02/uservideos-SQL.png" rel="lightbox[1065]"><img class="aligncenter size-full wp-image-1069" title="Data returned from this SQL statement" src="http://ericfickes.com/wp-content/uploads/2010/02/uservideos-SQL.png" alt="User 2 has two videos" width="499" height="220" /></a><br />
Here is how you would run the same query using .net&#8217;s LINQ to SQL.</p>
<pre class="brush: csharp;">
// create DB connection
var db = new DBCONN();
// run query
List&lt;video&gt; uvids = (
    from c in db.video
    join o in db.user_videos
    on c.vid equals o.vid
    where o.uid == 2
    select c
).ToList();
</pre>
<p>This query differs slightly from the screenshot below because I used it in a WCF Service.</p>
<p><a href="http://ericfickes.com/wp-content/uploads/2010/02/uservideos-LINQTOSQL.png" rel="lightbox[1065]"><img class="aligncenter size-full wp-image-1070" title="Same query run via LINQ to SQL" src="http://ericfickes.com/wp-content/uploads/2010/02/uservideos-LINQTOSQL.png" alt="Same data, different retrieval method" width="488" height="419" /></a></p>
<p>The variable DBCONN is my database connection that I established when mapping my DB.  If you are not familiar with how to set this up, use the Visual Studio&#8217;s &#8220;Add the ADO.NET Entity Data Model&#8221; wizard.  With your .net project open, right click your project, left click on &#8220;Add the ADO.NET Entity Data Model&#8221;.  This wizard will walk you through setting up everything you need to setup your DB model file ( edmx ), as well as setting up your database connection and saving it in web.config.</p>
<p>Jesse Liberty did a <a title="ADO.NET DataEntities and WCF Feeding a Silverlight DataGrid" href="http://silverlight.net/learn/tutorials/adonetdataentities-cs/" target="_blank">simple tutorial that uses this wizard in a WCF service application</a>.</p>
<p>I hope this helps somebody out.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/02/how-to-join-two-tables-using-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Select random value from a range of values</title>
		<link>http://ericfickes.com/2010/01/select-random-value-from-a-range-of-values/</link>
		<comments>http://ericfickes.com/2010/01/select-random-value-from-a-range-of-values/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 01:08:52 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[#table]]></category>
		<category><![CDATA[cte]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[mssql]]></category>
		<category><![CDATA[mssql2000]]></category>
		<category><![CDATA[mssql2005]]></category>
		<category><![CDATA[table variable]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1020</guid>
		<description><![CDATA[Earlier I blogged about creating random numbers using tsql functions.  Here are two techniques for selecting a random value from a pre-defined range of values in a tsql script.  The first technique uses a table variable ( MSSQL 2000 + ), and the second uses a Common Table Expression or CTE ( MSSQL 2005+ ). [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier I blogged about <a title="TSQL UDFs for generating random numbers" href="http://ericfickes.com/2009/09/generate-random-integers-using-tsql-udfs/" target="_blank">creating random numbers using tsql functions</a>.  Here are two techniques for selecting a random value from a pre-defined range of values in a tsql script.  The first technique uses a <a title="MSSQL 2000 let's you create table variables" href="http://msdn.microsoft.com/en-us/library/aa260638%28SQL.80%29.aspx" target="_blank">table variable</a> ( MSSQL 2000 + ), and the second uses a <a title="CTEs in MSSQL 2005 let you build queries a little differently" href="http://technet.microsoft.com/en-us/library/ms175972%28SQL.90%29.aspx" target="_blank">Common Table Expression</a> or CTE ( MSSQL 2005+ ).</p>
<h3>Select a random value using a table variable</h3>
<pre class="brush: sql;">

-- var to hold random integer
declare @field_val int

-- create table var to hold value range [ 0, 512, 1024, 2048, 4096 ]
-- inserting the first value sets the structure for the table variable
SELECT 0 AS 'num'
INTO #temp

-- insert data into table var
INSERT INTO #temp VALUES ( 512 )
INSERT INTO #temp VALUES ( 1024 )
INSERT INTO #temp VALUES ( 2048 )
INSERT INTO #temp VALUES ( 4096 )

-- assign random value
SELECT TOP 1 @field_val = num FROM #temp ORDER BY NEWID()

-- show value
SELECT @field_val

-- drop the table variable
DROP TABLE #temp
</pre>
<h3>Select a random value using a CTE</h3>
<pre class="brush: sql;">
-- define our data table
WITH data( car )
AS
(
	-- UNION together our range of values
	SELECT 'audi' AS 'car'
	UNION
	SELECT 'bmw' AS 'car'
	UNION
	SELECT 'infinity' AS 'car'
	UNION
	SELECT 'lexus' AS 'car'
	UNION
	SELECT 'porsche' AS 'car'
)
-- select a random value
SELECT TOP 1 car FROM data
ORDER BY NEWID()
</pre>
<p>Both of these techniques can be used with numbers or text.  Just be sure to mind your quotes, and variable datatypes.  Being able to pick a random value in data generation scripts has proven very useful.  I hope this helps somebody else out as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/01/select-random-value-from-a-range-of-values/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>I wonder if using Coldfusion9&#8242;s ORM would make this easier?</title>
		<link>http://ericfickes.com/2009/12/i-wonder-if-using-coldfusion9s-orm-would-make-this-easier/</link>
		<comments>http://ericfickes.com/2009/12/i-wonder-if-using-coldfusion9s-orm-would-make-this-easier/#comments</comments>
		<pubDate>Fri, 01 Jan 2010 02:50:09 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[adobe]]></category>
		<category><![CDATA[coldfusion]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[coldfusion9]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[structure]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=979</guid>
		<description><![CDATA[Rolling my own SQL solution Recently I was working on a medical website and was tasked with building a doctor directory page that had to pull data from three related tables.  For the viewers at home, here is a simplified view of my tables. The first version of the page was easy to whip up [...]]]></description>
			<content:encoded><![CDATA[<h2>Rolling my own SQL solution</h2>
<p>Recently I was working on a medical website and was tasked with building a <a href="http://sgpn.org/physicians.cfm" target="_blank">doctor directory page</a> that had to pull data from three related tables.  For the viewers at home, here is a simplified view of my tables.</p>
<div id="attachment_981" class="wp-caption aligncenter" style="width: 361px"><a href="http://ericfickes.com/wp-content/uploads/2009/12/doctor-practice-locations.png" rel="lightbox[979]"><img class="size-full wp-image-981" title="doctor-practice-locations" src="http://ericfickes.com/wp-content/uploads/2009/12/doctor-practice-locations.png" alt="Database tables : Doctors, Practices, and Locations" width="351" height="296" /></a><p class="wp-caption-text">Doctors, Practices, and Locations oh my</p></div>
<p>The first version of the page was easy to whip up because we were only showing primary location address which lives in the practices table.  ( NOTE : The diagram above was dumbed down to support this post ).  When the request came in to show all locations for each doctor&#8217;s practice, that&#8217;s when I had to put on my wizard hat and get tricky.</p>
<p>After some thinking I came up with two options for adding all locations for each doctor row :</p>
<ol>
<li>Build a second locations query for each doctor in the first query, then use code to merge the data together</li>
<li>Update the first query to include all necessary data, then use code to merge the data into a loopable structure</li>
</ol>
<p>Being a SQL junky, I decided to take the second route so I&#8217;m still only hitting the database once.  In the first version of this page, we always had one row per doctor and didn&#8217;t have to do any post processing of the data prior to sending to the page.  However, when the locations table gets added to our sql query, all of the doctor data gets duplicated for each location they are associated with, making the dataset look like this.</p>
<div id="attachment_984" class="wp-caption aligncenter" style="width: 474px"><a href="http://ericfickes.com/wp-content/uploads/2009/12/doctor-query.png" rel="lightbox[979]"><img class="size-full wp-image-984" title="doctor-query" src="http://ericfickes.com/wp-content/uploads/2009/12/doctor-query.png" alt="doctors, practice, and locations all in a single query" width="464" height="216" /></a><p class="wp-caption-text">When joining the third table, the first two get duplicated</p></div>
<p>Now that we&#8217;ve got all the data, you&#8217;ll notice that the doctor information gets duplicated.  This is where I built a cffunction to convert this query into a structure of individual doctors, each having an array of locations.  I used the doctor&#8217;s full name and id as the structure keys.  Great, now I can just loop through my new structure of doctors, then loop through each doctor.location array to draw the updated html table.  That is the goal here, but we&#8217;re not ready just yet.</p>
<p>If you&#8217;ve ever tried to <a title="cfloop: looping over a COM collection or structure" href="http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-71a6.html" target="_blank">loop over a Structure in Coldfusion</a>, you&#8217;ve probably noticed controlling the order of your data coming back can be tricky.  Here&#8217;s an example of what I&#8217;m talking about when looping through a structure.</p>
<div id="attachment_987" class="wp-caption aligncenter" style="width: 383px"><a href="http://ericfickes.com/wp-content/uploads/2009/12/simple-struct-loop.png" rel="lightbox[979]"><img class="size-full wp-image-987" title="simple-struct-loop" src="http://ericfickes.com/wp-content/uploads/2009/12/simple-struct-loop.png" alt="Looping through CF Structures, doesn't always loop in the order you'd expect" width="373" height="184" /></a><p class="wp-caption-text">Looping through a coldfusion structure can be a challenge</p></div>
<p>To get around this random order of looping through a structure, I did two steps prior to building the updated html table.</p>
<pre class="brush: coldfusion;">
	// UPDATE : extract key list ( DR full names ) so
	// you can sort the physicians my last name
	dr_list = StructKeyList( providers_struct );
	dr_list = ListSort( dr_list, &quot;textnocase&quot; );
</pre>
<p>This gives me an alphabetized list of all doctors inside my structure, which I convert to an array then loop through.  I know have a sorted loop that can pick all necessary doctor data out of my structure on command.  This solution took a little bit of time to figure, but wasn&#8217;t too bad.  After thinking about all the work needed to make this update, I wondered if using Coldfusion9&#8242;s Hibernate ORM would have made this update any easier.</p>
<h2>Porting SQL to ORM</h2>
<p>The first step in setting up  <a title="ColdFusion 9 has Hibernate built right in!" href="http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSD628ADC4-A5F7-4079-99E0-FD725BE9B4BD.html" target="_blank">Coldfusion9&#8242;s ORM</a> for this code is to enable the ORM in the application.</p>
<p>At the top of my Application.cfc I added the following lines.</p>
<pre class="brush: coldfusion;">
	&lt;cfscript&gt;
		// enable ORM
		this.ormenabled = true;

		// my datasource name, setup in the CFAdmin
		this.datasource = &quot;mysql-test&quot;;

		// the folder in my app where the cfc mapping files are location
		this.ormsettings.cfclocation = &quot;mappings&quot;;

		// this wasn't setup automatically for me
		this.ormsettings.dialect = &quot;MySQL&quot;;
	&lt;/cfscript&gt;
</pre>
<p>If you haven&#8217;t setup ORM in your Coldfusion9 application before, be sure to bookmark <a title="How do I configure ORM in Coldfusion9" href="http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSED380324-6CBE-47cb-9E5E-26B66ACA9E81.html" target="_blank">this livedoc page on configuring ORM</a>.  It will give you all the lowdown on all the fancy ORM bells and whistles.</p>
<p>After ORM is enabled, it was time to create my Hibernate mapping files for each of the database tables involved in this code.  For convenience sake, I went the CFC route, and only mapped the columns required for this example.  There are a number of ways to <a title="Define ORM mapping in Coldfusion9" href="http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WS53C28604-E798-4175-97AE-D7BDF124056C.html" target="_blank">define ORM mappings, refer to this livedocs page to find out more.</a> Here are my three hibernate mapping cfcs.</p>
<p><strong>doctor.cfc</strong></p>
<pre class="brush: coldfusion;">
&lt;cfcomponent persistent=&quot;true&quot; entityname=&quot;Doctor&quot; table=&quot;providers&quot;&gt;
    &lt;cfproperty name=&quot;id&quot; column=&quot;provider_id&quot; generator=&quot;increment&quot;&gt;

    &lt;!--- one to many relationship Doctor.practice = Practice ---&gt;
    &lt;cfproperty name=&quot;practice&quot; fieldtype=&quot;one-to-one&quot; cfc=&quot;PRACTICE&quot; fkcolumn=&quot;practice_id&quot;&gt;

    &lt;cfproperty name=&quot;PracticeId&quot; column=&quot;practice_id&quot; insert=&quot;false&quot; update=&quot;false&quot;&gt;

    &lt;cfproperty name=&quot;FirstName&quot; column=&quot;first_name&quot;&gt;
    &lt;cfproperty name=&quot;LastName&quot; column=&quot;last_name&quot;&gt;
    &lt;cfproperty name=&quot;status&quot; column=&quot;status&quot;&gt;
    &lt;cfproperty name=&quot;is_midlevel&quot; column=&quot;is_midlevel&quot;&gt;
&lt;/cfcomponent&gt;
</pre>
<p><strong>practice.cfc</strong></p>
<pre class="brush: coldfusion;">
&lt;cfcomponent persistent=&quot;true&quot; entityname=&quot;Practice&quot; table=&quot;practices&quot;&gt;
	&lt;!--- tie this column back to Doctor.practice_id ---&gt;
	&lt;cfproperty name=&quot;id&quot; column=&quot;practice_id&quot; fieldtype=&quot;id&quot; generator=&quot;foreign&quot; params=&quot;{property='Doctor'}&quot;&gt;

	&lt;!--- Relate locations to this practice via Locations.practice_id and Locations.active = 1 ---&gt;
        &lt;cfproperty name=&quot;locations&quot; type=&quot;array&quot; fieldtype=&quot;one-to-many&quot; cfc=&quot;Location&quot; fkcolumn=&quot;practice_id&quot; params=&quot;{property='Location'}&quot; where=&quot;active = 1&quot;&gt;

    &lt;cfproperty name=&quot;name&quot; column=&quot;practice_name&quot;&gt;
    &lt;cfproperty name=&quot;active&quot; column=&quot;active&quot;&gt;
&lt;/cfcomponent&gt;
</pre>
<p><strong>location.cfc</strong></p>
<pre class="brush: coldfusion;">
&lt;cfcomponent persistent=&quot;true&quot; entityname=&quot;Location&quot; table=&quot;locations&quot;&gt;
	&lt;cfproperty name=&quot;id&quot; column=&quot;location_id&quot; fieldtype=&quot;id&quot;&gt;

	&lt;cfproperty name=&quot;practice_id&quot; column=&quot;practice_id&quot;&gt;

    &lt;cfproperty name=&quot;address1&quot; column=&quot;address1&quot;&gt;
    &lt;cfproperty name=&quot;address2&quot; column=&quot;address2&quot;&gt;
    &lt;cfproperty name=&quot;city&quot; column=&quot;city&quot;&gt;
    &lt;cfproperty name=&quot;state&quot; column=&quot;state&quot;&gt;
    &lt;cfproperty name=&quot;zipcode&quot; column=&quot;zipcode&quot;&gt;
    &lt;cfproperty name=&quot;phone&quot; column=&quot;phone&quot;&gt;
    &lt;cfproperty name=&quot;active&quot; column=&quot;active&quot;&gt;
&lt;/cfcomponent&gt;
</pre>
<p>At this point we have three ORM entities that are mapped to the three database tables.  If you look closely, you&#8217;ll notice that relationships have also been defined for doctors to practice, and practice to locations.  Setting up the relationships at the mapping level takes care of physically joining the three tables together via sql.  Also, while it&#8217;s pretty straight forward reading a blog with working code, I&#8217;m not going to pretend I got these relationships setup first try.  It&#8217;s simple relating two tables together, but finding the right combination for doctror &gt; practice &gt; locations was tricky.  I did a lot of this to figure this part out.</p>
<pre class="brush: coldfusion;">
&lt;cfscript&gt;
// load doctors
dr_list = ORMExecuteQuery( &quot;FROM Doctor WHERE status = 'Active' AND provider_id = 1&quot; );
// load a practice
// practice = ORMExecuteQuery( &quot;FROM Practice WHERE practice_id = 1&quot; );
// load a location
// location = ORMExecuteQuery( &quot;FROM Location&quot; );
&lt;/cfscript&gt;

&lt;cfdump var=&quot;#dr_list#&quot; /&gt;
&lt;cfabort /&gt;
</pre>
<p><span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; line-height: 19px; white-space: normal; font-size: 13px;">You can find out more about <a title="How to define relationships with Coldfusion9 ORM" href="http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WS5FFD2854-7F18-43ea-B383-161E007CE0D1.html" target="_blank">defining ORM relationships on this livedocs page</a>.</span></p>
<p>With the hard stuff out of the way, we&#8217;re down to two steps.  First it&#8217;s time to port my cfquery that grabs the data, and the cffunction that converts the query into our loopable doctor structure.  Are you ready for this?</p>
<pre class="brush: coldfusion;">
dr_list = ORMExecuteQuery( &quot;from Doctor WHERE status = 'Active' AND is_midlevel = 0 ORDER BY last_name, first_name&quot; );
</pre>
<p>To give you the full idea of how much code was shrunk down to a single line, here are the two cffunctions used to query and massage the data into a useable structure.</p>
<pre class="brush: coldfusion;">
	&lt;!--- Retrieve listing of all active providers in the app  ---&gt;
    &lt;cffunction name=&quot;getAllActiveProviders&quot; access=&quot;public&quot; returntype=&quot;struct&quot;&gt;

		&lt;cfquery name=&quot;providers_qry&quot; DATASOURCE=&quot;#request.dsn#&quot; USERNAME=&quot;#request.dbuser#&quot; PASSWORD=&quot;#request.dbpswd#&quot;&gt;
            SELECT	DISTINCT

					p.provider_id,
            		CONCAT( p.first_name, ' ', p.last_name ) AS 'full_name',
                    p.first_name,
                    p.last_name,

    	            p2.practice_name,

					l.address1,
                    l.address2,
                    l.city,
                    l.state,
                    l.zipcode,
                    l.phone

            FROM	providers p, practices p2

            LEFT OUTER JOIN locations l
            ON p2.practice_id = l.practice_id AND l.active = 1

            WHERE	p.status = 'Active'
            AND		p.practice_id = p2.practice_id
            AND		is_midlevel = 0

            ORDER BY	p.last_name, p.first_name
        &lt;/cfquery&gt;

		&lt;!--- return a translated structure ---&gt;
		&lt;cfreturn providersQryToStruct( providers_qry ) /&gt;

    &lt;/cffunction&gt;

	&lt;!--- Translates the providers query into a Struct that has a row per doctor, each containing an Array for location(s) ---&gt;
	&lt;cffunction name=&quot;providersQryToStruct&quot; access=&quot;public&quot; returntype=&quot;struct&quot;&gt;

    	&lt;cfargument name=&quot;providers_qry&quot; type=&quot;query&quot; required=&quot;yes&quot;&gt;

		&lt;cfscript&gt;
		this_dr = &quot;&quot;;
		last_dr = &quot;&quot;;
		// array of provider arrays
		providers_struct = StructNew();

		// loop through qry and flatten into single row with Location = Array
		// The key to this qry is provider_name+provider_id
		for( xx = 1; xx &lt;= providers_qry.RecordCount; xx++ )
		{
			// set key to this row [ LAST_NAME+FIRST_NAME+PROVIDER_ID ]
			this_dr = providers_qry.LAST_NAME[ xx ] &amp; providers_qry.FIRST_NAME[ xx ] &amp; providers_qry.PROVIDER_ID[ xx ];

			// clean up DR name
			this_dr = Replace( this_dr, &quot; &quot;, &quot;&quot; );
			this_dr = Replace( this_dr, &quot;,&quot;, &quot;&quot; );
			this_dr = Replace( this_dr, &quot;.&quot;, &quot;&quot; );

			// got same doctor?
			if( this_dr != last_dr )
			{
				// append to array
				provider = StructNew();
				// FILL UP PROVIDER
				provider['full_name'] = providers_qry[&quot;full_name&quot;][ xx ];
				provider['practice_name'] = providers_qry['practice_name'][ xx ];

				// location array
				provider['location'] = ArrayNew(1);

				// add first location
				loc = StructNew();
				loc['address1']	 = providers_qry['address1'][ xx ];
				loc['address2']	 = providers_qry['address2'][ xx ];
				loc['city']		 = providers_qry['city'][ xx ];
				loc['state']	 = providers_qry['state'][ xx ];
				loc['zipcode']	 = providers_qry['zipcode'][ xx ];
				loc['phone']	 = providers_qry['phone'][ xx ];

				// add location struct to array
				ArrayAppend( provider['location'], loc );

				// Add to master struct
				providers_struct[ this_dr ] = provider;
			}
			else
			{
				// add first location
				loc = StructNew();
				loc['address1']	 = providers_qry['address1'][ xx ];
				loc['address2']	 = providers_qry['address2'][ xx ];
				loc['city']		 = providers_qry['city'][ xx ];
				loc['state']	 = providers_qry['state'][ xx ];
				loc['zipcode']	 = providers_qry['zipcode'][ xx ];
				loc['phone']	 = providers_qry['phone'][ xx ];

				// Append to this DR's location array
				ArrayAppend( providers_struct[ this_dr ]['location'], loc );
			}

			// store this_dr in last_dr for next iteration
			last_dr = this_dr;
		}

		return providers_struct;
        &lt;/cfscript&gt;

    &lt;/cffunction&gt;
</pre>
<p>After going through the brain fry of figuring out ORM relationships, replacing over one hundred lines of code with only a single line really made my day.  Now it was time for the final step, porting the cfml that draws the html table into using the ORM collection instead.<br />
The porting of the cfml that draws the doctor table was a piece of cake.  The updates were so easy it was almost not worth showing, but I&#8217;m including just to complete the picture.</p>
<p><strong>The original sql loop code</strong></p>
<pre class="brush: coldfusion;">
    &lt;!--- use dr_list as sorted list. use each DR key to pick out data from providers_struct ---&gt;
    &lt;cfloop list=&quot;#dr_list#&quot; index=&quot;xx&quot;&gt;
    &lt;tr&gt;

        &lt;td&gt;#providers_struct[ xx ]['full_name']#&lt;/td&gt;

        &lt;td&gt;#providers_struct[ xx ]['practice_name']#&lt;/td&gt;

        &lt;td&gt;
        &lt;!--- loop through array of location structures ---&gt;
        &lt;cfloop from=&quot;1&quot; to=&quot;#ArrayLen( providers_struct[ xx ]['location'] )#&quot; index=&quot;yy&quot;&gt;
            &lt;address&gt;
            &lt;cfset loc = #providers_struct[ xx ]['location'][ yy ]#&gt;
            &lt;li&gt;#loc.address1#, #loc.address2#
            #loc.city#, #loc.state# #loc.zipcode#
            &lt;br /&gt;
            &lt;b&gt;#loc.phone#&lt;/b&gt;
            &lt;/li&gt;
            &lt;/address&gt;
        &lt;/cfloop&gt;
        &lt;/td&gt;

    &lt;/tr&gt;
    &lt;/cfloop&gt;
</pre>
<p><strong>The new ORM loop code</strong></p>
<pre class="brush: coldfusion;">
	&lt;!--- loop through parent query ---&gt;
    &lt;cfloop array=&quot;#dr_list#&quot; index=&quot;xx&quot;&gt;
    &lt;tr&gt;

    	&lt;!--- retrieve properties using ORM's getProperty() syntax ---&gt;
        &lt;td&gt;#xx.getFirstName()# #xx.getLastName()#&lt;/td&gt;

        &lt;td&gt;#xx.getPractice().getName()#&lt;/td&gt;

        &lt;td&gt;
		&lt;!--- loop through locations collection Doctor &gt; Practice &gt; Location(s)  ---&gt;
        &lt;cfloop array=&quot;#xx.getPractice().getLocations()#&quot; index=&quot;loc&quot;&gt;

            &lt;address&gt;
                &lt;li&gt;#loc.getAddress1()#, #loc.getAddress2()#
                #loc.getCity()#, #loc.getState()# #loc.getZipcode()#
                &lt;br /&gt;
                &lt;b&gt;#loc.getPhone()#&lt;/b&gt;
                &lt;/li&gt;
            &lt;/address&gt;

        &lt;/cfloop&gt;
        &lt;/td&gt;

    &lt;/tr&gt;
    &lt;/cfloop&gt;
</pre>
<p>A few things I&#8217;d like to point out in the new ORM loop code</p>
<ol>
<li>ORMExecuteQuery returned a data collection that I can loop through without post-processing</li>
<li>When retrieving object properties, use the get<strong>PropertyName</strong>() syntax.  EX : doctor.getFirstName() instead of doctor.FirstName</li>
<li>Practice.locations was declared as an Array collection, but you could use Structure as well.</li>
<li>To get the ORMExecuteQuery record count, use ArrayLen.</li>
</ol>
<h2>Did ORM make this easier?</h2>
<p>I&#8217;d say yes it did.  Mapping my tables via code, including the relationships, really saved time writing SQL.  Funny thing, while I was porting this over, I actually found a few data and code bugs in the home grown solution that I didn&#8217;t catch before.  Once the dust had settled I still had one difference in the home grown versus ORM code, and that turned out to be duplicated location rows.</p>
<p>The other thing that I noticed thanks to our good friend cfdump, is all the extra functionality that comes along with the objects returned from ORM.  On top of having a populated data object, you also have magical getters, setters, and other useful methods to work with your data objects.  To see what I mean, fire an ORMExecuteQuery and run your variable through CFDUMP.</p>
<p>To sum up, I&#8217;m really starting to buy into using ORMs.  Since I know and love SQL, I&#8217;ve been anti ORM for too long.  Having said that, I&#8217;m not fully advocating going ORM for everything.  Pretty much every project I work on these days is powered by some datasource, but I don&#8217;t really need all the ORM baggage for simple sites.  Now for large applications, or any site large enough to need at least two people, I&#8217;d give ORM a chance.  I still have lots of ins and outs to learn about using Hibernate, but it is definitely simple enough to get jamming right away.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2009/12/i-wonder-if-using-coldfusion9s-orm-would-make-this-easier/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Generate random integers using tsql UDFs</title>
		<link>http://ericfickes.com/2009/09/generate-random-integers-using-tsql-udfs/</link>
		<comments>http://ericfickes.com/2009/09/generate-random-integers-using-tsql-udfs/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 19:55:48 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[utility]]></category>
		<category><![CDATA[integer]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[random integer generation]]></category>
		<category><![CDATA[random number]]></category>
		<category><![CDATA[sql2005]]></category>
		<category><![CDATA[udf]]></category>
		<category><![CDATA[user defined functions]]></category>
		<category><![CDATA[view]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=928</guid>
		<description><![CDATA[Ever need to generate random numbers from the integer family?  I had this need on a project so I whipped up these four tsql User Defined Functions to help with this task.  There are four functions in all, one for tinyint, smallint, int, and bigint.  Additionally, you will need to create one VIEW since you [...]]]></description>
			<content:encoded><![CDATA[<p>Ever need to generate random numbers from the integer family?  I had this need on a project so I whipped up these four <a title="( udf ) CREATE FUNCTION on MSDN" href="http://msdn.microsoft.com/en-us/library/ms186755.aspx" target="_blank">tsql User Defined Functions</a> to help with this task.  There are four functions in all, one for tinyint, smallint, int, and bigint.  Additionally, you will need to create one VIEW since you can not fire the tsql function RAND() inside of a udf.</p>
<p>With these functions, you can generate random integers in their native range.</p>
<pre class="brush: sql;"> SELECT dbo.getRandomInt( NULL, NULL ) </pre>
<p>Or you can restrict your random integers to a range of your liking.</p>
<pre class="brush: sql;"> SELECT dbo.getRandomInt( 1000, 1000000000) </pre>
<p>Just as a reminder, here are the native ranges for these four<a title="int, bigint, smallint, and tinyint (Transact-SQL)" href="http://msdn.microsoft.com/en-us/library/ms187745.aspx" target="_blank"> integer types as supported by MS SQL Server 2005</a></p>
<table border="1" cellspacing="7" cellpadding="7" rules="rows">
<tbody>
<tr>
<td style="text-align: right;"><strong>bigint</strong></td>
<td>-2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807)</td>
</tr>
<tr>
<td style="text-align: right;"><strong>int</strong></td>
<td>-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)</td>
</tr>
<tr>
<td style="text-align: right;"><strong>smallint</strong></td>
<td>-2^15 (-32,768) to 2^15-1 (32,767)</td>
</tr>
<tr>
<td style="text-align: right;"><strong>tinyint</strong></td>
<td>0 to 255</td>
</tr>
</tbody>
</table>
<p>Each of these functions have the same structure and primarily differ only by the integer type&#8217;s native range.  Here is the guts of one of the UDFs in case you want just the facts.</p>
<pre class="brush: sql;">/******************************************************************************
Generate a random int
-------------------------------------------------------------------------------
USAGE :
 -- Get random int in the default range -2,147,483,648 to 2,147,483,647
 SELECT dbo.getRandomInt( NULL, NULL )

 -- Get random tinyint within a specific range
 SELECT dbo.getRandomInt( 1000, 30000 )

REQUIREMENT : Since you can't call RAND() inside of a UDF,
this function is dependant on the following VIEW vRand :

-- BEGIN VIEW
 -- This is only a helper VIEW since currently you can not use RAND() in a UDF
 -- DROP VIEW vRand
 CREATE VIEW [dbo].[vRand]
 AS
 SELECT RAND() AS 'number'
-- END VIEW

******************************************************************************/

USE SmartEarth
GO

IF OBJECT_ID (N'getRandomInt') IS NOT NULL
 DROP FUNCTION getRandomInt
GO

CREATE FUNCTION getRandomInt( @min_in int, @max_in int )
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
-------------------------------------------------------------------------------
 DECLARE @max int,
 @min int,
 @rand NUMERIC( 18,10 ),
 @max_big NUMERIC( 38, 0 ),
 @rand_num NUMERIC( 38, 0 ),
 @out int;

 -- define this datatype's natural range
 SET @min = -2147483648    -- -2,147,483,648
 SET @max = 2147483647    -- 2,147,483,647

 -- Check to see if a range has been passed in.
 -- Otherwise, set to default tinyint range
 IF( @min_in is not null AND @min_in &gt; @min )
 SET @min = @min_in

 IF( @max_in is not null AND @max_in &lt; @max )
 SET @max = @max_in
 -- end range check

 -- get RAND() from VIEW since we can't use it in UDF
 SELECT @rand = number FROM vRand

 -- CAST @max so the number generation doesn't overflow
 SET @max_big = CAST( @max AS NUMERIC(38,0) )

 -- make the number
 SELECT @rand_num = ( (@max_big + 1) - @min ) * @rand + @min;

 -- validate rand
 IF( @rand_num &gt; @max )
 -- too big
 SET @out = @max
 ELSE IF ( @rand_num &lt; @min )
 -- too small
 SET @out = @min
 ELSE
 -- just right, CAST it
 SET @out = CAST( @rand_num AS int )

 -- debug
 -- SELECT @min_in AS 'min_in', @max_in AS 'max_in', @min AS 'min', @max AS 'max', @rand, @rand_num AS 'rand_num', @out AS 'out'

 -- return appropriate
 RETURN @out;

-------------------------------------------------------------------------------

END;
GO</pre>
<h3>So where do you get the code?</h3>
<p>You can view all functions and view online at the following <a title="GIST @ GITHUB" href="http://gist.github.com/" target="_blank">gist.github</a> urls:</p>
<ul>
<li><a title="tsql view vRand" href="http://gist.github.com/179910" target="_blank">VIEW : vRand</a></li>
<li><a title="tsql udf getRandomTinyint" href="http://gist.github.com/179904" target="_blank">UDF : getRandomTinyint</a></li>
<li><a title="tsql udf getRandomSmallint" href="http://gist.github.com/179906" target="_blank">UDF : getRandomSmallint</a></li>
<li><a title="tsql udf getRandomInt" href="http://gist.github.com/179907" target="_blank">UDF : getRandomInt</a></li>
<li><a title="tsql udf getRandomBigint" href="http://gist.github.com/179908" target="_blank">UDF : getRandomBigint</a></li>
</ul>
<p>Or you can just <a title="download all the tsql view and functions in a single zip file" href="http://ericfickes.com/code/tsqlRandomIntFunctions.zip" target="_blank">download all the source code in one zip file here</a>.</p>
<p>Hopefully this will help somebody out.  If you&#8217;re a DBA or just a tsql wizard, let me know what you think.  Can I do these functions a better way?  Is this already built into SQL2005 and I just didn&#8217;t know it?  All of this tsql was written against SQL Server 2005, but I&#8217;m pretty sure it would work on SQL2000 and SQL2008 as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2009/09/generate-random-integers-using-tsql-udfs/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
