<?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>SharpDeveloper &#187; SQL</title>
	<atom:link href="http://www.sharpdeveloper.net/content/archive/category/sql/feed" rel="self" type="application/rss+xml" />
	<link>http://www.sharpdeveloper.net/content</link>
	<description>C# articles and tutorials on SharpDeveloper.NET</description>
	<lastBuildDate>Thu, 12 Aug 2010 15:17:23 +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>Improve SQL Server Plan Execution Speed With Foreign Keys and constraints</title>
		<link>http://www.sharpdeveloper.net/content/archive/2010/01/11/improve-sql-server-plan-execution-speed-with-foreign-keys-and-constraints.aspx</link>
		<comments>http://www.sharpdeveloper.net/content/archive/2010/01/11/improve-sql-server-plan-execution-speed-with-foreign-keys-and-constraints.aspx#comments</comments>
		<pubDate>Mon, 11 Jan 2010 15:01:25 +0000</pubDate>
		<dc:creator>Sameer</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.sharpdeveloper.net/content/?p=503</guid>
		<description><![CDATA[Its been a while since I have posted, and I thought this was too amazing to NOT share Apparently, using Check Constraints and adding Foreign Keys not only improves the quality of your database through ensuring referential integrity and data integrity in general, apparently it also helps the Query Analyzer design better plans! Take a [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I have posted, and I thought this was too amazing to NOT share</p>
<p>Apparently, using Check Constraints and adding Foreign Keys not only improves the quality of your database through ensuring referential integrity and data integrity in general, apparently it also helps the Query Analyzer design better plans!</p>
<p>Take a look at this post:</p>
<ul>
<li>13 Things you should know about <a href="http://www.simple-talk.com/sql/t-sql-programming/13-things-you-should-know-about-statistics-and-the-query-optimizer/?utm_source=simpletalk&amp;utm_medium=email&amp;utm_content=13Things20100111&amp;utm_campaign=SQL">statistics and the query optimizer</a>, jump to <strong>Point 9</strong>.</li>
<li>Also, incase you are wondering what he means by &#8220;trusted constraint&#8221; and &#8220;non trusted constraints&#8221;, it would be &#8216;non trusted&#8217; if you allowed existing non-complying data in the table to stay in there. <a href="http://sqlblog.com/blogs/tibor_karaszi/archive/2008/01/12/non-trusted-constraints.aspx">More here</a> on trusted constraints.</li>
</ul>
<h3  class="related_post_title">Other Interesting Posts</h3><ul class="related_post"><li><a href="http://www.sharpdeveloper.net/content/archive/2008/05/08/php-vs-aspnet.aspx" title="PHP VS. ASP.NET">PHP VS. ASP.NET</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/05/25/creating-sqlparameters-best-practices.aspx" title="Creating SqlParameters Best Practices">Creating SqlParameters Best Practices</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/07/11/what-makes-a-sharp-developer-part-1.aspx" title="Are You a Sharp Developer?? (Part 1)">Are You a Sharp Developer?? (Part 1)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.sharpdeveloper.net/content/archive/2010/01/11/improve-sql-server-plan-execution-speed-with-foreign-keys-and-constraints.aspx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Copy A Database Diagram To Another Database</title>
		<link>http://www.sharpdeveloper.net/content/archive/2008/04/19/copy-a-database-diagram-to-another-database.aspx</link>
		<comments>http://www.sharpdeveloper.net/content/archive/2008/04/19/copy-a-database-diagram-to-another-database.aspx#comments</comments>
		<pubDate>Sat, 19 Apr 2008 17:18:34 +0000</pubDate>
		<dc:creator>Sameer</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://migrate.sharpdeveloper.net/content/?p=210</guid>
		<description><![CDATA[For some reason SQL Server doesn&#8217;t have an easy way to &#34;Create TO&#34; for database diagrams, unlike stored procedures, functions ,etc. Here is how you can achieve moving a database diagram (or copying a database diagram) in SQL Server 2005 use Old_Database go --this will copy your database diagrams into a temporary table select * [...]]]></description>
			<content:encoded><![CDATA[<p>For some reason SQL Server doesn&#8217;t have an easy way to &quot;Create TO&quot; for database diagrams, unlike stored procedures, functions ,etc.</p>
<p>Here is how you can achieve moving a database diagram (or copying a database diagram) in SQL Server 2005</p>
<pre class="brush: sql">
use Old_Database

go

--this will copy your database diagrams into a temporary table

select * into dbo.#tempsysdiagrams from sysdiagrams

use New_Database

go

insert into sysdiagrams ([name],principal_id,version,definition)
select [name],principal_id,version,definition from dbo.#tempsysdiagrams where [name]=&#039;Name_of_your_Diagram&#039;
</pre>
<p>
That&#8217;s it, so easy.</p>
<h3  class="related_post_title">Other Interesting Posts</h3><ul class="related_post"><li><a href="http://www.sharpdeveloper.net/content/archive/2008/05/08/php-vs-aspnet.aspx" title="PHP VS. ASP.NET">PHP VS. ASP.NET</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/05/25/creating-sqlparameters-best-practices.aspx" title="Creating SqlParameters Best Practices">Creating SqlParameters Best Practices</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/07/11/what-makes-a-sharp-developer-part-1.aspx" title="Are You a Sharp Developer?? (Part 1)">Are You a Sharp Developer?? (Part 1)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.sharpdeveloper.net/content/archive/2008/04/19/copy-a-database-diagram-to-another-database.aspx/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Check if a record exists using IF EXISTS instead of COUNT(*) for increased performance</title>
		<link>http://www.sharpdeveloper.net/content/archive/2007/08/12/if-exists-instead-of-count-equals-increased-performance.aspx</link>
		<comments>http://www.sharpdeveloper.net/content/archive/2007/08/12/if-exists-instead-of-count-equals-increased-performance.aspx#comments</comments>
		<pubDate>Sun, 12 Aug 2007 20:54:33 +0000</pubDate>
		<dc:creator>Sameer</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://migrate.sharpdeveloper.net/content/?p=175</guid>
		<description><![CDATA[How to find out if a record exists in a table efficiently using the IF EXISTS keyword, and 2) How to test and optimize two queries to see which is faster using SQL Server Management Studio.  Includes screenshots]]></description>
			<content:encoded><![CDATA[<p>Summary: </p>
<ol>
<li>How to find out if a record exists in a table efficiently using the IF EXISTS keyword, and&nbsp; </li>
<li>How to test two queries to see which is faster using SQL Server Management Studio.&nbsp; This articles teaches you how to tune and tweak your queries.
    </li>
</ol>
<p>If you are writing a query to find out if a record exists in your table, you might not be doing it the fastest way if you are using COUNT(*).<br />
i.e. SELECT COUNT(*) FROM USERS where USERID=@UID <br />
and then from your code you are checking if the count is greater than 0.</p>
<p>This can be efficiently re-written as </p>
<p><span style="font-weight: bold;">IF EXISTS (SELECT * FROM USERS WHERE USERID=@UID) select 1 else select 0</span><br style="font-weight: bold;" /><br />
<br />
That is very easy.&nbsp; It is much more efficient.<br />
How do we know its more efficient?</p>
<p>You can use SQL Server Management Studio to find out.&nbsp; What you have to do is write your two queries,</p>
<pre class="brush: sql">
--testing variables
declare @UID int
set @UID = 1
--actual query 1
SELECT COUNT(*) FROM USERS where USERID=@UID
--actual query 2
IF EXISTS (SELECT * FROM USERS WHERE USERID=@UID) select 1 else select 0
</pre>
<p></span>Select all, Click on the button to generate the query execution plan (screenshot below &#8211; click to enlarge)</p>
<p><a href="http://www.sharpdeveloper.net/screenshots/Display_Plan.png"><img height="67" border="0" width="645" src="/screenshots/Display_Plan.png" alt="Display Execution Plan (click to enlarge)" /></a></p>
<p>And you will see that it will give you a percentage breakdown for each query.&nbsp; The first two lines, creating testing variables, you can ignore.&nbsp; However, looking at the last two queries will show you the breakdown of effort required to run those queries.&nbsp; It will be similar to 99% for query 1, and 1% for query 2.&nbsp; This is a quick way to find which query should run faster and you can tweak the queries until you get the results you want.</p>
<p><a href="http://www.sharpdeveloper.net/screenshots/Execution_Plan_Results.png"><img height="461" border="0" width="640" src="/screenshots/Execution_Plan_Results.png" alt="Execution Plan Results (click to enlarge)" /></a></p>
<p>What that means is 98% of the work has to go into the first query (out of 2) and 2% for the second.&nbsp; That gives you a rough &#8230; idea&#8230; of which one is faster.&nbsp; Sometimes it will be more evenly broken down, closer to 50/50, and in that case they are roughly equivalent.</p>
<h3  class="related_post_title">Other Interesting Posts</h3><ul class="related_post"><li><a href="http://www.sharpdeveloper.net/content/archive/2008/05/08/php-vs-aspnet.aspx" title="PHP VS. ASP.NET">PHP VS. ASP.NET</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/05/25/creating-sqlparameters-best-practices.aspx" title="Creating SqlParameters Best Practices">Creating SqlParameters Best Practices</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/07/11/what-makes-a-sharp-developer-part-1.aspx" title="Are You a Sharp Developer?? (Part 1)">Are You a Sharp Developer?? (Part 1)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.sharpdeveloper.net/content/archive/2007/08/12/if-exists-instead-of-count-equals-increased-performance.aspx/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using DISTINCT in Aggregate Functions</title>
		<link>http://www.sharpdeveloper.net/content/archive/2007/07/05/using-distinct-in-aggregate-functions.aspx</link>
		<comments>http://www.sharpdeveloper.net/content/archive/2007/07/05/using-distinct-in-aggregate-functions.aspx#comments</comments>
		<pubDate>Thu, 05 Jul 2007 11:10:06 +0000</pubDate>
		<dc:creator>Sameer</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://migrate.sharpdeveloper.net/content/?p=161</guid>
		<description><![CDATA[The T-SQL aggregate functions (COUNT, SUM, AVG, MIN, and MAX) can all be used with the DISTINCT keyword to calculate them on distinct columns only.]]></description>
			<content:encoded><![CDATA[<p>By Ashiq Alibhai</p>
<p><strong>Note: </strong>This article applies to T-SQL; it may or may not work on other varients of SQL.</p>
<p>Many of us are familiar with T-SQL aggregate functions&#8211;COUNT, SUM, AVG, MIN, and MAX.&nbsp; However, one often-neglected feature is that you can use these with the DISTINCT keyword.</p>
<p>Imagine you have the following SQL:<font face="Courier New" size="2"></p>
<p></font></p>
<pre class="brush: sql">
CREATE TABLE #TEMP (
  VAL INT)

INSERT INTO #TEMP
VALUES     (1)

INSERT INTO #TEMP
VALUES     (1)

INSERT INTO #TEMP
VALUES     (1)

INSERT INTO #TEMP
VALUES     (2)

INSERT INTO #TEMP
VALUES     (3)

INSERT INTO #TEMP
VALUES     (3)

INSERT INTO #TEMP
VALUES     (7)

SELECT COUNT(VAL),
       COUNT(DISTINCT (VAL))
FROM   #TEMP
</pre>
<p>&#8230;will give you the results <strong>7</strong> and <strong>4</strong>.&nbsp; Similarly, SUM(DISTINCT(val)) will give you <strong>13</strong>&nbsp;while the non-distinct gives you <strong>18</strong>.</p>
<p>Note that while MIN and MAX are also DISTINCTable, doing so doesn&#8217;t really add any additional value.</p>
<h3  class="related_post_title">Other Interesting Posts</h3><ul class="related_post"><li><a href="http://www.sharpdeveloper.net/content/archive/2008/05/08/php-vs-aspnet.aspx" title="PHP VS. ASP.NET">PHP VS. ASP.NET</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/05/25/creating-sqlparameters-best-practices.aspx" title="Creating SqlParameters Best Practices">Creating SqlParameters Best Practices</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/07/11/what-makes-a-sharp-developer-part-1.aspx" title="Are You a Sharp Developer?? (Part 1)">Are You a Sharp Developer?? (Part 1)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.sharpdeveloper.net/content/archive/2007/07/05/using-distinct-in-aggregate-functions.aspx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Use SqlParameterCache (Caching Sql Parameters)</title>
		<link>http://www.sharpdeveloper.net/content/archive/2007/06/29/how-to-use-sqlparametercache-caching-sql-parameters.aspx</link>
		<comments>http://www.sharpdeveloper.net/content/archive/2007/06/29/how-to-use-sqlparametercache-caching-sql-parameters.aspx#comments</comments>
		<pubDate>Fri, 29 Jun 2007 20:35:06 +0000</pubDate>
		<dc:creator>Sameer</dc:creator>
				<category><![CDATA[.NET articles]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://migrate.sharpdeveloper.net/content/?p=133</guid>
		<description><![CDATA[This article describes how to cache your SqlParameters.    Using the SqlParameterCache allows you to increase efficiency of calling stored procedures and even on executing regular SQL queries!]]></description>
			<content:encoded><![CDATA[<p>This article describes how to cache your SqlParameters.&nbsp; If you have code that is regularly executed, and that uses a stored procedure, you can benefit from this.&nbsp; This information, as well as how to properly use this, is very hard to find, even on <a href="http://www.google.ca/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=nOl&amp;q=GetspParameterSet&amp;btnG=Search&amp;meta=">Google</a>. (Don&#8217;t worry, you don&#8217;t need to spend all that time looking, the information is already here for you!)</p>
<p>There is a function that Microsoft built that will allow you to get the parameter information from the database stored procedure, and that doesn&#8217;t require you to re-build your parameter array every time.&nbsp; The only thing you will need to do is set the values of the parameters.</p>
<p>What some people don&#8217;t realize, is that a similar approach can be taken with regular SQL queries that are not stored procedures! </p>
<p>The downside is that the first call will be slower, because it will need to cache the parameters, however, for each extra call, it will be faster because the parameters are already created.</p>
<p>How can you do this?&nbsp; You first create your parameters, and store it in the call by calling SqlParameterCache.<span style="font-weight: bold;">CacheParameterSet()</span></p>
<p>Then you call SqlParameterCache.<span style="font-weight: bold;">GetCachedParameterSet()</span> to get the cached result.&nbsp; If the result is null, then you can store the parameters in the cache, otherwise you already have it cached!</p>
<p>Here is an example in VB.NET of how to use SqlParameterCache.<span style="font-weight: bold;">CacheParameterSet()</p>
<pre class="brush: vb">
Dim cachedParams as SqlParameter() = SqlHelperParameterCache.GetCachedParameterSet(Config.connstring,strSql)

if cachedParams is nothing then

Dim params as SqlParameter() = { _
    New SqlParameter(&quot;@userID&quot;, userID), _
    New SqlParameter(&quot;@timestamp&quot;, timestamp), _
    New SqlParameter(&quot;@email&quot;,email), _
    New SqlParameter(&quot;@timesLoaded&quot;,5), _
    New SqlParameter(&quot;@country&quot;,country), _
    New SqlParameter(&quot;@source&quot;,source) _
}

SqlHelperParameterCache.CacheParameterSet(Config.connstring,strSql,params)
    cachedParams = params
else
    cachedParams(0).Value = userID
    cachedParams(1).Value = timestamp
    cachedParams(2).Value = email
    cachedParams(3).Value = 5
    cachedParams(4).Value = country
    cachedParams(5).Value = source
End If

SqlHelper.ExecuteNonQuery(Config.connstring, CommandType.Text, strSql, cachedParams)
</pre>
<p>
Now the down side to this, is you lose your ability to dynamically create your SQL parameters (i.e. it depends on the order of your SQL parameters).</p>
<p>Related articles:</p>
<ul>
<li><a href="http://sharpdeveloper.net/content/archive/2007/05/25/creating-sqlparameters-best-practices.aspx">Using Dynamically Created SqlParameter Arrays</a></li>
<li><a href="http://www.sharpdeveloper.net/content/archive/2007/06/15/creating-maintainable-database-queries-in-c-with-source-code.aspx">Creating Maintainable Database Queries In C# (with source code)</a></li>
<li><a href="http://www.sharpdeveloper.net/content/articles/sqlhelper-source-code.aspx">SqlHelper Source Code, Microsoft Application Blocks</a></li>
</ul>
<h3  class="related_post_title">Other Interesting Posts</h3><ul class="related_post"><li><a href="http://www.sharpdeveloper.net/content/archive/2008/05/08/php-vs-aspnet.aspx" title="PHP VS. ASP.NET">PHP VS. ASP.NET</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/05/25/creating-sqlparameters-best-practices.aspx" title="Creating SqlParameters Best Practices">Creating SqlParameters Best Practices</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/07/11/what-makes-a-sharp-developer-part-1.aspx" title="Are You a Sharp Developer?? (Part 1)">Are You a Sharp Developer?? (Part 1)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.sharpdeveloper.net/content/archive/2007/06/29/how-to-use-sqlparametercache-caching-sql-parameters.aspx/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Search Trigger Text SQL Server 2005</title>
		<link>http://www.sharpdeveloper.net/content/archive/2007/06/26/search-trigger-text-sql-server-2005.aspx</link>
		<comments>http://www.sharpdeveloper.net/content/archive/2007/06/26/search-trigger-text-sql-server-2005.aspx#comments</comments>
		<pubDate>Tue, 26 Jun 2007 13:02:01 +0000</pubDate>
		<dc:creator>Sameer</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://migrate.sharpdeveloper.net/content/?p=127</guid>
		<description><![CDATA[How to search if a trigger contains certain text in SQL Server 2005: 

SELECT OBJECT_NAME(id) 
FROM syscomments 
WHERE [text] LIKE '%your_search_here%' AND OBJECTPROPERTY(id, 'IsTrigger') = 1 
GROUP BY OBJECT_NAME(id)]]></description>
			<content:encoded><![CDATA[<p>If you want to search triggers for text in SQL Server 2005, here is how you can do it.&nbsp; You would execute this in the case that you are looking for a trigger that updates a certain table, but you cannot find it, and you do not want to go through all the tables one by one, here is what you can execute:</p>
<pre class="brush: sql">
SELECT OBJECT_NAME(id)
FROM syscomments
WHERE [text] LIKE &#039;%your_search_here%&#039; AND OBJECTPROPERTY(id, &#039;IsTrigger&#039;) = 1
GROUP BY OBJECT_NAME(id)
</pre>
<p>And&nbsp;here is how you can search <a href="http://www.knowdotnet.com/articles/storedprocfinds.html">SQL server stored procedures</a> (external link).</p>
<h3  class="related_post_title">Other Interesting Posts</h3><ul class="related_post"><li><a href="http://www.sharpdeveloper.net/content/archive/2008/05/08/php-vs-aspnet.aspx" title="PHP VS. ASP.NET">PHP VS. ASP.NET</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/05/25/creating-sqlparameters-best-practices.aspx" title="Creating SqlParameters Best Practices">Creating SqlParameters Best Practices</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/07/11/what-makes-a-sharp-developer-part-1.aspx" title="Are You a Sharp Developer?? (Part 1)">Are You a Sharp Developer?? (Part 1)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.sharpdeveloper.net/content/archive/2007/06/26/search-trigger-text-sql-server-2005.aspx/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Guid Or Int Primary Key?</title>
		<link>http://www.sharpdeveloper.net/content/archive/2007/06/25/guid-or-int-primary-key.aspx</link>
		<comments>http://www.sharpdeveloper.net/content/archive/2007/06/25/guid-or-int-primary-key.aspx#comments</comments>
		<pubDate>Mon, 25 Jun 2007 18:14:01 +0000</pubDate>
		<dc:creator>Sameer</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://migrate.sharpdeveloper.net/content/?p=125</guid>
		<description><![CDATA[When designing a database, and creating the tables and schema, we have to choose carefully what we want our primary key to be. There are many different aspects to this.   This article discusses the benefits of using a GUID over an Integer primary key.]]></description>
			<content:encoded><![CDATA[<div>When designing a database, and creating the tables and schema, we have to choose carefully what we want our primary key to be.&nbsp;There are many different aspects to this.&nbsp;One aspect is do we want to use a natural key, or a surrogate key?&nbsp;An example of a natural key would be like a SIN or SSN number to represent a person.&nbsp;An example of a surrogate key would be an autonumber column in a database that starts with the value 1 and increases.&nbsp;Both of them have different pros and cons.&nbsp;The natural key if not chosen wisely can have duplicates and cause problems, and may also require you to join on multiple columns.&nbsp;For example, if your last name is your primary key, you will definitely run into cases where you will need a second column, say First Name, to differentiate between different records.&nbsp;In this case, you may even need to use a third one in the case of two people having the same first and last name.&nbsp;Surrogate keys do not suffer from this problem, but are meaningless in themselves (i.e. Record 4151 is much less meaningful than say Employee S Alibhai)</div>
<div>&nbsp;</div>
<div>If we have decided to go with a surrogate key, we have a couple of choices, at the least.&nbsp;This article will discuss the benefits of using a GUID datatype over an Integer for your primary key.</div>
<div>
First of all, what is a GUID? &ldquo;A Globally Unique Identifier or GUID is a special type of identifier used in software applications in order to provide a reference number which is unique in the context for which it is used, for example, in defining the internal reference for a type of access point in a software application, or for creating unique keys in a database. While each generated GUID is not guaranteed to be unique, the total number of unique keys is so large that the probability of the same number being generated twice is very small.&rdquo; (Wikipedia)&nbsp;This idea is so awesome, you can just keep generating GUIDs and never worry about a conflict.&nbsp;It&rsquo;s not like phone numbers that we run out of them so quickly (especially since cell phones became so popular) that we have to add new area codes, you can just use a GUID and not worry about it!</div>
<div>&nbsp;</div>
<div><strong>GUIDs ensure global uniqueness.</strong> &nbsp;Lets say you are one patent office out of 15,000 and you are issuing patents.&nbsp;If you issue a patent using Guids, you can be guaranteed that there is no other patent office that issued a patent with the same GUID as you!</div>
<div>&nbsp;</div>
<div><strong>GUIDs can be moved across databases nicely (no need to renumber existing keys).</strong>&nbsp;This means that even if you have a distributed database holding different sets of records from one table, you are garaunteed that when you merge them, you will not have any duplicate keys.&nbsp;For example, if you had one database for each sales office, and each sale had a unique key that was a GUID, you will never have two sales with the same GUID.</div>
<div>&nbsp;</div>
<div><strong>GUIDs reduce the number of joins required.&nbsp;</strong>If you have a hierarchal relationship in a database, say you have a county, that contains school, and a school contains a class, and a class contains students, here is two ways we can do this.&nbsp;</div>
<div><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Select * from students where classID=5 and schoolID=3 and countyID=1</span></div>
<div>This is because each county can have a school numbered 1, and each school can have a class numbered 5.. So to ensure uniqueness, we have to add more to our where clause.</p>
<p>However, if we were doing this with GUID, we can just do the following instead:</p></div>
<div><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Select * from students where classID=&rsquo;D59B58D1-4A46-4ED1-888F-00450556DA9A&rsquo;</span></div>
<div>&nbsp;</div>
<div>In this case, there is no possible way (well, maybe one in a quintillion) that there are two classes with the ID &rsquo;D59B58D1-4A46-4ED1-888F-00450556DA9A&rsquo;</div>
<div>&nbsp;</div>
<div>However, GUID has a larger data size, and you might want to take that into consideration.&nbsp;</div>
<div>&nbsp;</div>
<div>In conclusion, I feel that the benefits outweigh the costs.&nbsp;In one case, I have been able to pass a GUID and have much shorter queries rather than passing multiple sets of information that made my life much much easier.&nbsp;If I had a choice, I would go for GUID</div>
<div>&nbsp;</div>
<div>Reference: Programming Microsoft ADO.NET 2.0 Applications Advanced Topics, Glenn Johnson (Free Chapter)</div>
<div><a href="http://download.microsoft.com/download/f/c/7/fc7d048b-b7a5-4add-be2c-baaee38091e3/9780735621411_PrgrmADONET2.0AppsAdvTop_ch05.pdf"><font color="#606420">http://download.microsoft.com/download/f/c/7/fc7d048b-b7a5-4add-be2c-baaee38091e3/9780735621411_PrgrmADONET2.0AppsAdvTop_ch05.pdf</font></a></div>
<div>&nbsp;</div>
<h3  class="related_post_title">Other Interesting Posts</h3><ul class="related_post"><li><a href="http://www.sharpdeveloper.net/content/archive/2008/05/08/php-vs-aspnet.aspx" title="PHP VS. ASP.NET">PHP VS. ASP.NET</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/05/25/creating-sqlparameters-best-practices.aspx" title="Creating SqlParameters Best Practices">Creating SqlParameters Best Practices</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/07/11/what-makes-a-sharp-developer-part-1.aspx" title="Are You a Sharp Developer?? (Part 1)">Are You a Sharp Developer?? (Part 1)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.sharpdeveloper.net/content/archive/2007/06/25/guid-or-int-primary-key.aspx/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Creating Maintainable Database Queries In C# (with source code)</title>
		<link>http://www.sharpdeveloper.net/content/archive/2007/06/15/creating-maintainable-database-queries-in-c-with-source-code.aspx</link>
		<comments>http://www.sharpdeveloper.net/content/archive/2007/06/15/creating-maintainable-database-queries-in-c-with-source-code.aspx#comments</comments>
		<pubDate>Fri, 15 Jun 2007 22:17:17 +0000</pubDate>
		<dc:creator>Sameer</dc:creator>
				<category><![CDATA[.NET articles]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://migrate.sharpdeveloper.net/content/?p=119</guid>
		<description><![CDATA[7 tips on how to create maintainable database queries.  Create a data object, avoid stored procedures, build with stringbuilder, keep it together, code SQL over C#, use a SqlParameter Array, and Trust your judgement!]]></description>
			<content:encoded><![CDATA[<div><strong><font size="3">Creating Maintainable Database Queries In C#</font></strong></div>
<p><span style="font-weight: bold;">By Ashiq Alibhai</span></p>
<p><font>Many applications (and websites, especially) rely on some sort of database to get their work done.  As projects and teams grow beyond a one-person-working-in-his-garage model, you can&#8217;t rely on the fact that you, or someone who knows the query well, will be the one in charge of modifying it when the time comes.  So what are some of the practises you can implement in order to create <strong>easily-maintainable and understandable</strong> queries?</font></p>
</p>
<div><strong><font size="3">Create a Data Object!</font></strong></div>
<p>If you have a website, aim for three-tiered architecture and <strong>create objects in your App_Code folder (data/application tier) that call the database&mdash;</strong><span>don&#8217;t code the query directly in the class!  Or, if you have an application, </span><strong>create some centralized folders/classes to perform database queries</strong><span>.  The more you can abstract (eg. SomeObject.FetchData vs. SqlHelper.Execute&#8230;), the easier it will be if you have to switch data-sources later.</span></p>
<div><strong><font size="3"><br />
Avoid Stored Procedures!</font></strong></div>
<p><font>Stored procedures&#8211;while offering a dubious performance upgrade&#8211;also come with the tag that they are <strong>very difficult to maintain</strong>.  Not only will newbies to SQL become befuddled by the syntax, you need, but they <strong>require database-level permissions</strong><span> to modify it.  And, in terms of releasing, it adds the extra maintenance of </span><strong>having to propagate stored procedures along with data&mdash;</strong><span>as opposed to a query embedded in a .cs file.</span></font></p>
</p>
<div><strong><font size="3">Build with StringBuilder!</font></strong></div>
<p>C# string-concatenation requires creating a new buffer of the total length of both strings, then copying both into it.  If you use concatenation in several places, especially if your code gets run frequently, it may become a bottleneck.  Avoid it by using s<strong>tringBuilder.Append(&#8230;)</strong><span> instead of </span><strong>string1 + string2</strong>.</p>
<div><strong><font size="3"><br />
Keep it Together!</font></strong></div>
<p>As much as possible, <strong>keep your query in one piece and avoid breaking it up into parts as much as possible.</strong><span>  This makes your query more readable, and also more efficient (in terms of string-concatenation, which is very slow because it requires allocating space for a new string and copying over the original).  (You can even use the @ sign in front of your constant to allow you to break up the assignment over multiple lines without concatenating at each line &ndash; which, if you use proper indenting, also makes your query <strong>much easier to read</strong>.)</span></p>
<p style="margin-bottom: 0in;"><span>The only exception to keeping your query together is </span><strong>if you have if-conditions in a where clause</strong><span>, such as the following example:</span>
</p>
<pre class="brush: c#">
            StringBuilder queryBuilder = new StringBuilder();
            queryBuilder.Append(@&quot;
                SELECT
                    *
                FROM
                    Contacts
                    INNER JOIN ContactPurchases ON
                        Conacts.Id = ContactPurchases.ContactId
                    INNER JOIN Purchases ON
                        Purchases.Id = ContactPurchases.PurchaseId
                WHERE
                    Purchaser.Id = @purchaserId
            &quot;);

            if (targetDate != DateTime.MinValue)
            {
                queryBuilder.Append(&quot; AND Purchases.Date = @targetDate&quot;);
            }

            // ... similar checks and additions to the query
</pre>
<p>Of course, there are always reasons to break up query-building into more complicated logic&mdash;such as for-loops, cases, etc. as your application requires.  The trade-off is yours to consider!</p>
</p>
<div><strong><font size="3">Code SQL over C#!</font></strong></div>
<p>Wherever possible, <strong>code logic into the SQL query instead of the page&mdash;</strong><span>so functions like while-loops, cases, checking for null, etc. Should be done <em>inside</em><span style="font-style: normal;"> the query.</span></span></p>
<p style="font-style: normal;">Why?  Just like keeping your query in one piece, it allows anyone sufficiently skilled in SQL to read and understand the query without the control flow jumping all over the place.  Plus, it makes it easy to copy-paste the query and execute it.</p>
</p>
<div><strong><font size="3">Use an SqlParameter Array!</font></strong></div>
<p>If you have parameters to pass to your query<span>, you should be using SqlParameter instances in order to avoid potential SQL injections.  Additionally, instead of building your query line-by-line, like this:</span></p>
<pre class="brush: c#">
            SqlParameter[] parameters = newSqlParameter[2];
            parameters[0] = newSqlParameter(&quot;@purchaserId&quot;, purchaserId);
            parameters[1] = newSqlParameter(&quot;@targetDate&quot;, targetDate);

Build them using the array initializer, like this:

            SqlParameter[] parameters = {
                new SqlParameter(&quot;@purchaserId&quot;, purchaserId),
                new SqlParameter(&quot;@targetDate&quot;, targetDate)
            };
</pre>
<p>This has one main advantage over the array: it doesn&#8217;t require you to manually maintain the list (and count) of parameters, which can become a maintenance headache if the number goes over three or four parameters.&nbsp; Read more about <a href="http://www.sharpdeveloper.net/content/archive/2007/05/25/creating-sqlparameters-best-practices.aspx">using SqlParameter arrays</a>.
</p>
<div><strong><font size="3"><strong><br />
Trust Your Judgement!</strong></font></strong></div>
<p>Above all, <strong>trust your judgement and the judgement of your peers.</strong>  Sometimes, past (or existing) coders may choose to write queries certain ways.  Or maybe you feel that this <em>one </em><span style="font-style: normal;">piece of logic</span> really <em>should</em><span style="font-style: normal;"> be inside a C# for-loop.</span></p>
<p style="font-style: normal;">It&#8217;s up to you!  Ultimately, it&#8217;s all a trade-off, and the goal here is not to create the &quot;ultimate&quot; style of writing queries, but only to guide you towards building something that creates <strong>readable and maintainable queries.</strong></p>
<h3  class="related_post_title">Other Interesting Posts</h3><ul class="related_post"><li><a href="http://www.sharpdeveloper.net/content/archive/2008/05/08/php-vs-aspnet.aspx" title="PHP VS. ASP.NET">PHP VS. ASP.NET</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/05/25/creating-sqlparameters-best-practices.aspx" title="Creating SqlParameters Best Practices">Creating SqlParameters Best Practices</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/07/11/what-makes-a-sharp-developer-part-1.aspx" title="Are You a Sharp Developer?? (Part 1)">Are You a Sharp Developer?? (Part 1)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.sharpdeveloper.net/content/archive/2007/06/15/creating-maintainable-database-queries-in-c-with-source-code.aspx/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Prefix tables with dbo. in your SQL</title>
		<link>http://www.sharpdeveloper.net/content/archive/2007/05/29/prefix-tables-with-dbo-in-your-sql.aspx</link>
		<comments>http://www.sharpdeveloper.net/content/archive/2007/05/29/prefix-tables-with-dbo-in-your-sql.aspx#comments</comments>
		<pubDate>Tue, 29 May 2007 11:38:03 +0000</pubDate>
		<dc:creator>Sameer</dc:creator>
				<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://migrate.sharpdeveloper.net/content/?p=36</guid>
		<description><![CDATA[A power tip on increasing your query execution speed is to prefix your table and stored procedure names with dbo.  By prefixing with dbo, Our database makes one less call.  Normally, when you do not use the dbo keyword, on a query such as Select * from Users where UserID = @UserID, it will first check the user's schema to see if that table exists for them. ]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a SQL power tip &#8211; to speed up your query and stored procedure executions a bit.&nbsp; Prefix your tables and stored procedures with dbo.</p>
<p><span style="font-weight: bold;">Select * from dbo.[Users] where UserID = @UserID</span><br style="font-weight: bold;" /><br />
<br />
or</p>
<p><span style="font-weight: bold;">EXEC dbo.UsersLookup &#8230;.</p>
<p></span> By prefixing with dbo, Our database makes one less call.&nbsp; Normally, when you do not use the dbo keyword, on a query such as Select * from Users where UserID = @UserID, it will first check the user&#8217;s schema to see if that table exists for them.&nbsp; </p>
<p>i.e. if you are logged on as server administrator (sa), it will attempt to do a <br />
<span style="font-weight: bold;">Select * from sa.Users where UserID = @UserID<br />
</span><br />
Then, if that table does not exist under sa, it will try again under dbo (main schema)<br />
Normally, this is 1 extra redundant call that you want to avoid.</p>
<p>This helps the database engine encourage re-use and caching of queries.&nbsp; The database engine will have an easier time recognizing that this is the same query that was just called, and will be more likely to cache and re-use your execution and decrease execution run time.<br />
<span style="font-weight: bold;"></span></p>
<h3  class="related_post_title">Other Interesting Posts</h3><ul class="related_post"><li><a href="http://www.sharpdeveloper.net/content/archive/2008/05/08/php-vs-aspnet.aspx" title="PHP VS. ASP.NET">PHP VS. ASP.NET</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/05/25/creating-sqlparameters-best-practices.aspx" title="Creating SqlParameters Best Practices">Creating SqlParameters Best Practices</a></li><li><a href="http://www.sharpdeveloper.net/content/archive/2007/07/11/what-makes-a-sharp-developer-part-1.aspx" title="Are You a Sharp Developer?? (Part 1)">Are You a Sharp Developer?? (Part 1)</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.sharpdeveloper.net/content/archive/2007/05/29/prefix-tables-with-dbo-in-your-sql.aspx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
