<?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/tag/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>Eleven Coldfusion-ish tips from the field</title>
		<link>http://ericfickes.com/2011/02/eleven-coldfusion-ish-tips-from-the-field/</link>
		<comments>http://ericfickes.com/2011/02/eleven-coldfusion-ish-tips-from-the-field/#comments</comments>
		<pubDate>Sun, 20 Feb 2011 08:34:49 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[adobe]]></category>
		<category><![CDATA[coldfusion]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[asc]]></category>
		<category><![CDATA[cfml]]></category>
		<category><![CDATA[cfscript]]></category>
		<category><![CDATA[chr]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[listcontains]]></category>
		<category><![CDATA[listfind]]></category>
		<category><![CDATA[listhasvalue]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[parameterized query]]></category>
		<category><![CDATA[special character]]></category>
		<category><![CDATA[sproc]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[stored procedure]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1965</guid>
		<description><![CDATA[I&#8217;ve had this running list of Coldfusion tips on my wall for the last few years and it&#8217;s time to get these online.  All of the items in this list came from Coldfusion projects over the last few years, but &#8230; <a href="http://ericfickes.com/2011/02/eleven-coldfusion-ish-tips-from-the-field/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve had this running list of Coldfusion tips on my wall for the last few years and it&#8217;s time to get these online.  All of the items in this list came from Coldfusion projects over the last few years, but a good portion of these could easily be considered tips for server programmers.  I definitely run into the same items when programming Asp.NET.</p>
<p>There is no rhyme or reason here, just some things I felt need to be repeated.</p>
<h2>1. <a href="http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=functions_m-r_14.html" target="_blank">PreserveSingleQuotes</a>()</h2>
<p>This one came in really handy on a project requiring large text files to be imported into a MySQL database.  I used Coldfusion to upload and read the files into large INSERT chunks using <a href="http://dev.mysql.com/doc/refman/5.5/en/insert.html" target="_blank">MySQL&#8217;s multi &#8211; row INSERT syntax</a>. Code built the VALUES portion of the SQL, then I just fed the data into a function for insertion.</p>
<pre class="brush: sql; title: ; notranslate">
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
</pre>
<pre class="brush: coldfusion; title: ; notranslate">
	&lt;cfquery name=&quot;insert_data&quot; result=&quot;insert_result&quot; DATASOURCE=&quot;#request.dsn#&quot; USERNAME=&quot;#request.dbuser#&quot; PASSWORD=&quot;#request.dbpswd#&quot;&gt;
	INSERT INTO table
	( column1, column2, column3, column4, column5, column6, column7 )
	VALUES
	#PreserveSingleQuotes( insert_values )#
	&lt;/cfquery&gt;
</pre>
<h2>2. What if GENERATED_KEY doesn&#8217;t work?</h2>
<p>If you&#8217;re using MySQL and the GENERATED_KEY property of your cfquery objects isn&#8217;t populating, you can use <a href="http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_last-insert-id" target="_blank">LAST_INSERT_ID</a> instead.</p>
<pre class="brush: sql; title: ; notranslate">SELECT LAST_INSERT_ID();</pre>
<h2>3. Use ArrayAppend when building strings</h2>
<p>Classic performance tuning tip for just about any programming language.  Here I&#8217;ll give a Coldfusion example and keep it dead simple.  If you ever have to concatenate strings in code, user ArrayAppend instead.  Here are two loops that do the same thing.  If you run this code, you should notice loop1 takes forever, and loop2 is smoking fast.</p>
<p><strong>slow&#8230;..</strong></p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfscript&gt;
xx				= 100000;
insertString	= &quot;&quot;;

// do the loop
while( xx &gt; 0 ) {
	insertString &amp;= xx &amp; &quot; &quot;;
	xx--;
}

WriteOutput( insertString);
&lt;/cfscript&gt;
</pre>
<p><strong>FAST!</strong></p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfscript&gt;
xx				= 1000000;
insertArray		= ArrayNew(1);
// do the loop
while( xx &gt; 0 ) {
	ArrayAppend( insertArray, xx &amp; &quot; &quot; );
	xx--;
}

WriteOutput( ArrayToList( insertArray, &quot; &quot; ) );
ArrayClear( insertArray );
&lt;/cfscript&gt;
</pre>
<h2>4. If CSV, then CHR</h2>
<p>This one is simple, if you find yourself creating CSV or any other text file, use special characters when dealing with single and double quotes, etc.</p>
<ul>
<li>chr(9) = Tab</li>
<li>chr(34) = &#8221; double quote</li>
<li>chr(39) = &#8216; single quote</li>
</ul>
<p>And if you&#8217;re not sure of the correct code for the character you&#8217;re looking to use, just wrap that character in <a href="http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=functions_a-b_25.html" target="_blank">ASC()</a> and <a href="http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7ecf.html" target="_blank">WriteOutput</a> to the page.</p>
<h2>5. Use CFMail with GMail</h2>
<p>This is a no brainer, but with how difficult sending email can be with <em><a title="I love .NET, but it's a pain in the butt sometimes" href="http://www.google.com/search?sourceid=chrome&amp;ie=UTF-8&amp;q=send+email+with+ASP.NET" target="_blank">other languages</a></em>, I&#8217;m mentioning it here.</p>
<p><strong>Application.cfc</strong></p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfscript&gt;
	APPLICATION.mail.server		= &quot;smtp.gmail.com&quot;;
	APPLICATION.mail.port		= &quot;465&quot;;
	APPLICATION.mail.ssl		= true;
	APPLICATION.mail.user		= &quot;gmailAccount&quot;;
	APPLICATION.mail.pswd		= &quot;gmailPasssword&quot;;
&lt;/cfscript&gt;
</pre>
<p><strong>Emailer.cfm</strong></p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfmail to=&quot;work@ericfickes.com&quot;
		bcc=&quot;&quot;
		from=&quot;web@master.com&quot;
		subject=&quot;sending mail is easy with Coldfusion&quot;
		server=&quot;#application.mail.server#&quot;
		useSSL=&quot;#application.mail.ssl#&quot;
		port=&quot;#application.mail.port#&quot;
		username=&quot;#application.mail.user#&quot;
		password=&quot;#application.mail.pswd#&quot;&gt;
#emailBody#
&lt;/cfmail&gt;
</pre>
<h2>6. CFSCRIPT doesn&#8217;t know NULL?</h2>
<p>Another tip from the land of importing and exporting data.  While working with query objects in CFScript, for some reason I could never accurately detect for NULL values.  I tried all sorts of detection schemes and ended up just writing a hacky fail safe.  Please, if you have a better suggestion for *easy* NULL detection in CFSCript, add it in the comments below.</p>
<p><strong>utils.cfc</strong></p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;!---  Simple value getter with try / catch to get around NULL values
This function originated in a script where we always needed a &quot; &quot; even if
the value from the database was null.
---&gt;
&lt;cffunction name=&quot;qryGetString&quot; access=&quot;public&quot; returntype=&quot;string&quot;&gt;

&lt;cfargument name=&quot;data&quot; type=&quot;string&quot;&gt;

&lt;cftry&gt;
	&lt;cfscript&gt;
	return #data# &amp; &quot; &quot;;
	&lt;/cfscript&gt;

	&lt;cfcatch type=&quot;Any&quot;&gt;
		&lt;cfreturn &quot; &quot;/&gt;
	&lt;/cfcatch&gt;
&lt;/cftry&gt;

&lt;/cffunction&gt;
</pre>
<p><strong>Exporter.cfm</strong></p>
<pre class="brush: coldfusion; title: ; notranslate">
// largeish loop
tab = chr(9);
for( xx = 1; xx &lt;= queryObj.RecordCount; xx++ )
{
	// start the row
	this_row = 	utils_cfc.qryGetString( queryObj.FirstName[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.MiddleName[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.LastName[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.Suffix[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.MedicalTitle[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.email[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.practice_phone[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.practice_fax[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.practice_name[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.practice_address1[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.practice_address2[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.practice_city[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.practice_state[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.practice_zipcode[xx] ) &amp; tab &amp;
			utils_cfc.qryGetString( queryObj.hospital_affiliation[xx] ) &amp; tab;

	// do stuff with the data
}
</pre>
<h2>7. How I find list items</h2>
<h2><span style="font-size: 16px; color: #444444; line-height: 24px;">Ever notice the different behavior in the Coldfusion ListFind commands?  I ended up writing my own ListHasValue function in order to find exact pattern matching in a list.  I had a list of role ids in a list, and just couldn&#8217;t get the built in functions to tell me when my id was in the list without also matching on other ids.  This one makes sense when you run some code.</span></h2>
<p>The top of this sample as my custom ListHasValue() command, and the lower half does three simple loops counting from 1 to 100, and using ListFind, ListContains, and ListHasValue for number checking against the same list.</p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;!---
	Use this to do an exact pattern check for a value in a list.
	This is useful inside of a loop checking numbers against a number list.

	EX :

	list = &quot;91, 92&quot;

	if you loop from 1 - 100, ListFind and related CF functions will match
	on 1, 2, and 9.  Not just 91 and 92

	Use this when you're looping and you ONLY want to match on 91, or 92

---&gt;
&lt;cffunction name=&quot;ListHasValue&quot; access=&quot;public&quot; returntype=&quot;boolean&quot;&gt;

	&lt;cfargument name=&quot;list&quot; required=&quot;yes&quot; type=&quot;string&quot;&gt;
	&lt;cfargument name=&quot;value&quot; required=&quot;yes&quot; type=&quot;any&quot;&gt;

	&lt;cfscript&gt;
		// clean up to be safe
		list = trim( toString( list ) );

		// check to see if we have a *possible* match
		position = ListContains( list, value ) ;

		if( position &gt; 0 )
		{
			// NOTE : KEEP THE TRIM AND TOSTRING
			found_value = trim( toString( ListGetAt( list, position ) ) );

			if( Compare( value, found_value ) == 0 )
			{
				return true;
			}
		}

		// no match for you!
		return false;
	&lt;/cfscript&gt;

&lt;/cffunction&gt;

&lt;cfscript&gt;
list	= &quot;1, 11, 21, 31, 41, 51, 61, 71, 81, 91, 99&quot;;
xx		= 1;

WriteOutput( &quot;List = &quot; &amp; list &amp; &quot;&lt;hr&gt;&quot;);

while( xx &lt; 100 ) {
	if( ListContains( list, xx ) &gt; 0 )
	{
		WriteOutput( &quot;ListContains found &quot; &amp; xx &amp; &quot;&lt;br&gt;&quot; );
	}
    xx++;
}

WriteOutput(&quot;&lt;hr /&gt;&quot;);

xx = 1;
while( xx &lt; 100 ) {
	// ListFind
	if( ListFind( list, xx ) &gt; 0 )
	{
		WriteOutput( &quot;ListFind found &quot; &amp; xx &amp; &quot;&lt;br&gt;&quot; );
	}
    xx++;
}

WriteOutput(&quot;&lt;hr /&gt;&quot;);

xx = 1;
while( xx &lt; 100 ) {
    // Eric's ListHasValue
	if( ListHasValue( list, xx ) )
	{
		WriteOutput( &quot;ListHasValue found &quot; &amp; xx &amp; &quot;&lt;br&gt;&quot; );
	}
	xx++;
}
&lt;/cfscript&gt;
</pre>
<p>If you run this code on your Coldfusion server, you should notice the following results.  ListContains matches single digits from the loop that do not really exist in the list.  ListFind only finds the number 1?  And finally, my function does exactly what I needed it to do.  Tell me when a specific number exists in a list.</p>
<div id="attachment_1980" class="wp-caption alignnone" style="width: 240px"><a href="http://ericfickes.com/wp-content/uploads/2011/02/cf-list-find1.png" rel="lightbox[1965]"><img class="size-full wp-image-1980" title="cf-list-find" src="http://ericfickes.com/wp-content/uploads/2011/02/cf-list-find1.png" alt="CF ListFind function comparison" width="230" height="559" /></a><p class="wp-caption-text">Coldfusion ListFind functions don&#39;t always behave how I want them to</p></div>
<p><span style="font-size: 16px; color: #444444; line-height: 24px;"><br />
</span></p>
<h2>8. Make PDFs faster</h2>
<p>This could easily be it&#8217;s own topic, but I&#8217;ll say one thing about making PDFs faster with CFDocument.  Only put final content between &lt;cfdocument&gt; and &lt;/cfdocument&gt;.  That is, if you have any processing code, cfqueries, cfloops, inside of your cfdocument tag, your cfml page is running slower than it needs to be.  Here&#8217;s a simple example of one of my cfml pages that has only final content in the cfdocument tags.</p>
<p>The key to this example is moving all of my content creation code into an external file, then including at the top of my page. I always do a check for my main PDF_BODY variable, and then spit out my PDF document.</p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfinclude template=&quot;code/export_pdf_codefile.cfm&quot;&gt;

&lt;cfif PDF_BODY NEQ &quot;&quot;&gt;

    &lt;cfdocument	name=&quot;provider_profile&quot;
                format=&quot;PDF&quot;
                pagetype=&quot;A4&quot;
                mimetype=&quot;application/pdf&quot;
                orientation=&quot;portrait&quot;
                margintop=&quot;0&quot;
                marginbottom=&quot;0.2&quot;
                marginleft=&quot;0.2&quot;
                marginright=&quot;0.2&quot;
                &gt;
        &lt;cfoutput&gt;#PDF_BODY#&lt;/cfoutput&gt;
    &lt;/cfdocument&gt;

    &lt;!--- send directly to client ---&gt;
    &lt;cfheader name=&quot;Content-Disposition&quot; value=&quot;attachment; filename=#filename#&quot;&gt;
    &lt;cfcontent type=&quot;application/pdf&quot; variable=&quot;#provider_profile#&quot;&gt;

&lt;cfelse&gt;
	No PDF content found
&lt;/cfif&gt;
</pre>
<h2>9. Use parameterized queries</h2>
<p>This is a tip for all server side programmers whether you use Coldfusion, ASP, JSP, PBJ.  Use parameterized queries when doing any database interaction.  It&#8217;s too easy not to use, and you get protection from SQL Injection, as well as enforcing proper data types when speaking to your database.  This is something all server programmers should do regardless of your language, the sample below is for Coldfusion.</p>
<p><strong>BAD</strong></p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfquery name=&quot;tblInsert&quot; datasource=&quot;myDb&quot;&gt;
INSERT INTO	myTable
( col1, col2, col3, col4 )
VALUES
( '#Form.field1#', '#Form.field2#', '#Form.field3#' )
&lt;/cfquery&gt;
</pre>
<p><strong>GOOD</strong></p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfset val1 = Form.field1&gt;
&lt;cfset val2 = Form.field1&gt;
&lt;cfset val3 = Form.field1&gt;

&lt;cfquery name=&quot;tblInsert&quot; datasource=&quot;myDb&quot;&gt;
INSERT INTO	myTable
( col1, col2, col3, col4 )
VALUES
(
    &lt;cfqueryparam cfsqltype=&quot;cf_sql_varchar&quot; value=&quot;#val1#&quot; /&gt;,
    &lt;cfqueryparam cfsqltype=&quot;cf_sql_varchar&quot; value=&quot;#val2#&quot; /&gt;,
    &lt;cfqueryparam cfsqltype=&quot;cf_sql_varchar&quot; value=&quot;#val3#&quot; /&gt;
)
&lt;/cfquery&gt;
</pre>
<h2>10. Where&#8217;d the time go?</h2>
<p>For the good programmers already using parameterized queries, ever insert a timestamp into your database and find out the date is correct, but the time is always 12:00:00?  Take a closer look at the cfsqltype in your cfqueryparam, I had this exact problem and here&#8217;s what happened.</p>
<p>Using <strong>cf_sql_date does</strong> not include the full date and timestamp, just the date.</p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfqueryparam cfsqltype=&quot;cf_sql_date&quot; value=&quot;#paymentDate#&quot; /&gt;
</pre>
<p>&nbsp;</p>
<p>Using <strong>cf_sql_timestamp</strong> includes the full date and timestamp I was looking for.</p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfqueryparam cfsqltype=&quot;cf_sql_timestamp&quot; value=&quot;#paymentDate#&quot; /&gt;
</pre>
<h2>11. Stored Procedures are a little different</h2>
<p>This last one isn&#8217;t much of a tip, but more of a reminder to myself.  I do so much database work that stored procedures are just queries to me, but not so to Coldfusion and the CFQuery tag.  If you want to get data from a stored procedure, you need to use the <a href="http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_r-s_22.html" target="_blank">CFStoredproc</a> tag.  Here&#8217;s a sample of passing one argument into a stored procedure, and how to get the resulting data.</p>
<pre class="brush: coldfusion; title: ; notranslate">
&lt;cfstoredproc	datasource=&quot;myDb&quot; procedure=&quot;GetDataFaster&quot;&gt;

	&lt;cfprocparam type=&quot;in&quot; cfsqltype=&quot;cf_sql_integer&quot; value=&quot;#inputVar#&quot; /&gt;

	&lt;!--- specify sproc result here, cfstoredproc res != returned recordset ---&gt;
	&lt;cfprocresult name = sprocResult&gt;

&lt;/cfstoredproc&gt;

&lt;cfreturn #sprocResult.ColumnFromQuery#&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2011/02/eleven-coldfusion-ish-tips-from-the-field/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Today I took 30 minutes to save hours</title>
		<link>http://ericfickes.com/2011/01/today-i-took-30-minutes-to-save-hours/</link>
		<comments>http://ericfickes.com/2011/01/today-i-took-30-minutes-to-save-hours/#comments</comments>
		<pubDate>Tue, 04 Jan 2011 04:21:41 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[automation]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[bat]]></category>
		<category><![CDATA[batch]]></category>
		<category><![CDATA[batch file]]></category>
		<category><![CDATA[cli]]></category>
		<category><![CDATA[cmd]]></category>
		<category><![CDATA[command line]]></category>
		<category><![CDATA[cursor]]></category>
		<category><![CDATA[DECLARE]]></category>
		<category><![CDATA[del]]></category>
		<category><![CDATA[exec]]></category>
		<category><![CDATA[fetch]]></category>
		<category><![CDATA[fetch_status]]></category>
		<category><![CDATA[information_schema]]></category>
		<category><![CDATA[kill]]></category>
		<category><![CDATA[restore]]></category>
		<category><![CDATA[sproc]]></category>
		<category><![CDATA[sqlcmd]]></category>
		<category><![CDATA[sys]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[workflow]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1861</guid>
		<description><![CDATA[UPDATE &#8211; 1/6/2011 : Since writing this post I have bundled this entire reset process into a single windows batch file. In addition to restoring my database, I also have to remove temp files from my server, so it was &#8230; <a href="http://ericfickes.com/2011/01/today-i-took-30-minutes-to-save-hours/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><strong> </strong><strong>UPDATE &#8211; </strong><strong>1/6/2011 : </strong>Since writing this post I have bundled this entire reset process into a single <a title="How to use windows batch files" href="http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/batch.mspx?mfr=true" target="_blank">windows batch file</a>. In addition to restoring my database, I also have to remove temp files from my server, so it was time to go command line with all of this.</p>
<p>Here the contents of my batch file.</p>
<pre class="brush: plain; title: ; notranslate">
### DELETE TEMP FILES
del /q /f /s Z:\_FavoriteClient\_GIT_\webapp\invoices\* /f /s

### RESTORE DATABASE
sqlcmd -S &quot;localhost&quot; -i Z:\_FavoriteClient\_GIT_\sql\restoreBackup.sql
</pre>
<p>To use this in a .bat file, copy and paste the text into Notepad, then save as &#8220;restore.bat&#8221;.  Remember, you will need to wrap your filename.bat with quotes, otherwise Notepad will save the file as filename.bat.txt.</p>
<p>* The contents of restoreBackup.sql is listed below.</p>
<hr style="color: efefef;" size="1" noshade="noshade" />One of my favorite pastimes as a programmer is writing code that writes code, aka workflow automation.  It&#8217;s not something I do on every project, but I&#8217;ve been doing a lot of SQL Server development recently, and I&#8217;ve been having a lot of fun using the <a title="SQL 2008 RS Information Schema Views (Transact-SQL)" href="http://msdn.microsoft.com/en-us/library/ms186778.aspx" target="_blank">INFORMATION_SCHEMA views</a> to <a title="Use TSQL to generate Actionscript VO classes" href="http://ericfickes.posterous.com/tsql-sproc-generatetablevoclass" target="_blank">build VO classes</a>, forms representing tables, or just finding what tables have a specific column.  Today I took a 30 minute trip to the <a title="SQL 2008 SYS tables" href="http://msdn.microsoft.com/en-us/library/ms187406.aspx" target="_blank">SYS side</a> and wrote a tsql script that will save me hours.</p>
<p>The web application I&#8217;m working on is a payment processor made up of five steps.  In order to test I have to setup multiple sales for multiple clients, then log in as three different admin users to push the transactions through the system.  This gets my test transactions to the proper testable state.  The process of setting up testable transactions takes over 30 clicks, and once I hit step 3 of the wizard, my test transactions are completed in a way that I have to re-setup the test data ( 20 GOTO 10 ).</p>
<p>I thought about a handful of options, and ended up going with this solution.</p>
<ol>
<li>Setup all test transactions in web application by hand ( get the data ready )</li>
<li>Take a full database backup ( freeze the data )</li>
<li>Use TSQL script to drop all connections to my app&#8217;s db, then restore the database to the &#8220;testable&#8221; state from step 1 ( reset the DB )</li>
</ol>
<p>Here is my TSQL script</p>
<pre class="brush: sql; title: ; notranslate">
DECLARE @sessID int,
		@dbName varchar(50),
		@userName varchar(50),
		@backupFile varchar(200)

SET @dbName		= 'DA413'	-- your database name
SET @userName	= 'DA413'	-- sql user account to look for
SET @backupFile = 'D:\DB\Backup\DA413.bak' -- path to SQL backup file

-- use a cursor to store all session_ids
DECLARE session_cursor CURSOR
FOR
	SELECT	session_id
	FROM	sys.dm_exec_sessions
	WHERE	original_login_name = @userName

	-- open cursor and grab first row
	OPEN session_cursor
	FETCH NEXT FROM session_cursor INTO @sessID

	-- loop through session_ids
	WHILE @@FETCH_STATUS = 0
	BEGIN

		-- kill it
		-- using EXEC because the sproc kill does not like @variables
		EXEC('kill ' + @sessID)

		-- get the next session_id
		FETCH NEXT FROM session_cursor INTO @sessID
	END

-- cursor cleanup
CLOSE session_cursor
DEALLOCATE session_cursor

-- restore backup
USE master
	RESTORE DATABASE DA413
	FROM DISK = @backupFile
GO
</pre>
<p>A few notes about this script :</p>
<ul>
<li>I only need to disconnect my web application&#8217;s database user, not any user</li>
<li>I&#8217;m using the latest full backup, and not a specific database snapshot</li>
<li>The SPROC <a title="TSQL KILL sproc" href="http://technet.microsoft.com/en-us/library/ms173730.aspx" target="_blank">kill</a> doesn&#8217;t like @variables as input, so use <a title="TSQL EXEC" href="http://msdn.microsoft.com/en-us/library/ms188332.aspx" target="_blank">EXEC</a></li>
<li>Your web server doesn&#8217;t know the user was disconnected, so you&#8217;ll have to log back into your application.</li>
<li>If you use this technique, be sure to RERUN your backup if you add anything to the database ( EX : new table column, stored procedure, etc )</li>
<li>If you&#8217;re not the only person connected to this database, make sure you don&#8217;t disconnect anybody else using the same database name</li>
</ul>
<p>This solution is perfect for me because I have full control over my code, database, and server.  It&#8217;s also great because I can test my application, run a single sql script, and 10 seconds later I can test my application again.  While this solution is perfect for me, it&#8217;s probably best used as reference for others.  However, this technique of rolling back the database could be applied to <em>any</em> software application using SQL Server for it&#8217;s datasource.</p>
<p>Hope this helps somebody.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2011/01/today-i-took-30-minutes-to-save-hours/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>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[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 &#8230; <a href="http://ericfickes.com/2010/06/use-sql-to-insert-a-label-in-front-of-a-databound-list/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></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; title: ; notranslate">
&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; title: ; notranslate">
&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>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>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 &#8230; <a href="http://ericfickes.com/2010/02/how-to-join-two-tables-using-linq-to-sql/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></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; title: ; notranslate">
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; title: ; notranslate">
// 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>6</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 &#8230; <a href="http://ericfickes.com/2009/12/i-wonder-if-using-coldfusion9s-orm-would-make-this-easier/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></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; title: ; notranslate">
	// 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; title: ; notranslate">
	&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; title: ; notranslate">
&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; title: ; notranslate">
&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; title: ; notranslate">
&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; title: ; notranslate">
&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; title: ; notranslate">
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; title: ; notranslate">
	&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; title: ; notranslate">
    &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; title: ; notranslate">
	&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[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 &#8230; <a href="http://ericfickes.com/2009/09/generate-random-integers-using-tsql-udfs/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></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; title: ; notranslate"> 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; title: ; notranslate"> 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; title: ; notranslate">/******************************************************************************
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>4</slash:comments>
		</item>
		<item>
		<title>The &#8216;Why learn SQL&#8217; list has begun</title>
		<link>http://ericfickes.com/2008/12/the-why-learn-sql-list-has-begun/</link>
		<comments>http://ericfickes.com/2008/12/the-why-learn-sql-list-has-begun/#comments</comments>
		<pubDate>Sat, 20 Dec 2008 04:48:20 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[cool]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[social]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[learn]]></category>
		<category><![CDATA[makefive]]></category>
		<category><![CDATA[top5 lists]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=363</guid>
		<description><![CDATA[Today&#8217;s new social service is a top5 list making site called www.makefive.com.  I haven&#8217;t gotten too deep into the site yet, but it looks like a lot of fun.  I definitely dig the idea, especially if you can tie this &#8230; <a href="http://ericfickes.com/2008/12/the-why-learn-sql-list-has-begun/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Today&#8217;s new social service is a top5 list making site called <a title="MakeFive.com - top5 lists for you" href="http://www.makefive.com" target="_blank">www.makefive.com</a>.  I haven&#8217;t gotten too deep into the site yet, but it looks like a lot of fun.  I definitely dig the idea, especially if you can tie this into all your other social outlets.</p>
<p>My first list is a rough sketch of reasons why you should learn SQL.  I love SQL, and have been collecting reasons why you should learn it, but just haven&#8217;t gotten around to getting my ideas down.  I&#8217;m hoping this list will be the motivation I need to get my love for SQL out on the internets.<br />
<!-- MakeFive Widget begin --><br />
<script src="http://widget.makefive.com/widgetframe.php?topicId=1870&amp;uid=1181&amp;widgetId=98a5757f49300a04" type="text/javascript"></script></p>
<p>See more: <a title="Why you should learn SQL" href="http://www.makefive.com/categories/technology/computing/why-you-should-learn-sql" target="_blank">Why you should learn SQL</a></p>
<p><!-- MakeFive Widget end --></p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2008/12/the-why-learn-sql-list-has-begun/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The phones have SQL, so does AIR</title>
		<link>http://ericfickes.com/2008/11/the-phones-have-sql/</link>
		<comments>http://ericfickes.com/2008/11/the-phones-have-sql/#comments</comments>
		<pubDate>Sun, 30 Nov 2008 03:45:15 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[smartphone]]></category>
		<category><![CDATA[sqlite]]></category>
		<category><![CDATA[windows mobile]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=318</guid>
		<description><![CDATA[It&#8217;s pretty damn cool that the smartphones of today can run SQL databases. Google&#8217;s Android has SQLite, which you can read about here. Apple&#8217;s iPhone also has SQLite. The SQLite library lets you embed a lightweight SQL database into your &#8230; <a href="http://ericfickes.com/2008/11/the-phones-have-sql/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s pretty damn cool that the smartphones of today can run SQL databases.</p>
<p>Google&#8217;s Android has SQLite, <a title="Understanding Android's SQLite packages" href="http://code.google.com/android/reference/android/database/sqlite/package-summary.html" target="_blank">which you can read about here.</a></p>
<p>Apple&#8217;s iPhone also has SQLite.</p>
<blockquote><p>The SQLite library lets you embed a lightweight SQL database into your application without running a separate remote database server process. From your application, you can create local database files and manage the tables and records in those files. The library is designed for general purpose use but is still optimized to provide fast access to database records.  The header file for accessing the SQLite library is located in &lt;iPhoneSDK&gt;/usr/include/sqlite3.h, where &lt;iPhoneSDK&gt; is the path to the target SDK in your Xcode installation directory. For more information about using SQLite, go to <a title="SQLite.org" href="http://www.sqlite.org" target="_blank">http://www.sqlite.org</a>.</p></blockquote>
<p>Microsoft even has a mobile version of their SQL Server.  Of course they can&#8217;t seem to stick with a name for it.  SQL Server Mobile, SQL Everywhere, SQL Server Compact Edition, and currently <a title="SQL Server for Windows Mobile" href="http://www.microsoft.com/Sqlserver/2005/en/us/compact.aspx" target="_blank">SQL Server Compact 3.5</a></p>
<p>I&#8217;m just getting over the excitement about <a title="Adobe AIR" href="http://www.adobe.com/products/air/" target="_blank">Adobe&#8217;s AIR</a> having SQLite, and now my phone can run it too.  This makes for some interesting development choices.  In my opinion, being able to have a database on your device is one of the final steps of making a device a true platform.  Now it&#8217;s time to get dirty with some Sqlite coding.</p>
<p>By the way, I&#8217;d put this on my list of reasons why you should learn SQL.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2008/11/the-phones-have-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

