<?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>eugene.K &#187; MSSQL</title>
	<atom:link href="http://ekdd.co.il/category/mssql/feed/" rel="self" type="application/rss+xml" />
	<link>http://ekdd.co.il</link>
	<description>web developer to web developers</description>
	<lastBuildDate>Tue, 22 Sep 2009 06:05:41 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>HOWTO: Properly connect to MSSQL database</title>
		<link>http://ekdd.co.il/howto-properly-connect-to-mssql-database/</link>
		<comments>http://ekdd.co.il/howto-properly-connect-to-mssql-database/#comments</comments>
		<pubDate>Sat, 19 Sep 2009 19:20:07 +0000</pubDate>
		<dc:creator>eugene</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MSSQL]]></category>
		<category><![CDATA[connection string]]></category>

		<guid isPermaLink="false">http://ekdd.co.il/?p=130</guid>
		<description><![CDATA[There are many ways you can connect to a database in ASP.NET, the way i’m going to explain here based on “try and error” during my development years. I will try to explain why i do each step and what errors i had in the past so you may prevent these in your web applications. [...]]]></description>
			<content:encoded><![CDATA[<p>There are many ways you can connect to a database in ASP.NET, the way i’m going to explain here based on “try and error” during my development years. I will try to explain why i do each step and what errors i had in the past so you may prevent these in your web applications. Experienced programmer should know each of these steps and may disagree so discussion is open to debate.</p>
<p><span id="more-130"></span></p>
<p><strong>What will you gain from using this technique ?</strong></p>
<ol>
<li>Organized in one place connection strings will prevent you from searching and replacing every time you change connection string or its name.</li>
<li>You will always have a connection closed and disposed from memory even if there was an error which prevented you from getting to the line where Sqlconnection is closed and disposed from memory.</li>
</ol>
<p><strong>Step one — Keep all connection string at one place<br />
</strong></p>
<p>Instead of hard coding every single place you connect to database you can set connection string value inside of web.config or a class. There is no rule where set connection string better in a class or web.config but any ASP.NET developer will first look at ConnectionStrings section of web.config so it would be better to keep connection strings where they belong to.</p>
<pre class="brush: xml">

&lt;connectionStrings&gt;
&lt;add name=&quot;Dismark&quot; connectionString=&quot;Data Source=.\sqlexpress;Initial Catalog=Dismark;Integrated Security=True;Pooling=False&quot; providerName=&quot;Sytem.Data.SqlClient&quot;/&gt;
&lt;add name=&quot;Support&quot; connectionString=&quot;Data Source=.\sqlexpress;Initial Catalog=Support;Integrated Security=True;Pooling=False&quot; providerName=&quot;Sytem.Data.SqlClient&quot;/&gt;
&lt;/connectionStrings&gt;
</pre>
<p>As you can see there are two database connection strings, it is important to name databases and give  connection string names according to what they represent. “Dismark” is an application name so i name the database and connection string the same name so in two month i won’t be needed to guess what “ConnectionString1” means. “Support” is a centralized database for costumer ticket support system because the client has few applications while it is much easier to work with centralized support ticket system rather have one per application. So each time you create an application for yourself or for a client ask yourself what whether are gonna be other applications or not because you can create external centralized Support, ErrorReports and Billing databases.</p>
<p><strong>Step two — Make connections easier to use by having a function to retrieve already opened SqlConnection.</strong></p>
<p>This step reduces amount of code you need to write each time you connect to database with your code. For example we will create a class inside of a App_Code folder named DB which will handle all our connections.</p>
<p>This is how your old code could look like</p>
<pre class="brush: c#">

using System;
using System.Configuration;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[&quot;Dismark&quot;].ConnectionString);
cn.Open();
// code goes here
cn.Close();
cn.Dispose();
}
}
</pre>
<p>Instead lets create a DB class with two functions, each function connects to specific database, opens a connection and returns to the caller.This way we will write less code each time we connect to database, it will be easier to change if for some reason we will change a database moved to another server or we will have to change connection string name.</p>
<pre class="brush: c#">

using System;
using System.Configuration;
using System.Data.SqlClient;

public class DB
{
public static SqlConnection connectToDismark()
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[&quot;Dismark&quot;].ConnectionString);
cn.Open();
return cn;
}
public static SqlConnection connectToSupport()
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[&quot;Support&quot;].ConnectionString);
cn.Open();
return cn;
}
}
</pre>
<p>This is a call to these functions from page where you connect to a database. As you can see there are less code to write and we don’t have to remember database’s exact name as Visual Studio’s intellisense helps us when we type DB class name.</p>
<pre class="brush: c#">
SqlConnection cn2 = DB.connectToDismark();
// code goes here
cn2.Close();
cn2.Dispose();
</pre>
<p><strong>Step 3 — Encapsulation of connection within using block<br />
</strong></p>
<p>As you see there are two methods remain, connection.Close() and connection.Dispose(). One obviously closes the connection to database and other one disposes it from memory. We need to keep in mind that sometimes we won’t reach those lines of code because of error of some kind (ie. bad input from user which cause an error to <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx" rel="nofollow" title="SqlCommand class"  target="_blank">SqlCommand </a>object). Which means connection will remain open until Sql Server closes it. Not good practice as server may have limit or still use resources to keep the connection alive, instead of that we can encapsulate connection within using block which will automatically close() and dispose() connection when we leave its scope. Lets see how its done.</p>
<pre class="brush: c#">
using (SqlConnection cn3 = DB.connectToDismark())
{
// code goes here
}
</pre>
<p><a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx" rel="nofollow" title="SqlConnection Class"  target="_blank">Sqlconnection</a> class inherits from <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="nofollow" title="IDisposable Interface"  target="_blank">IDisposable</a> interface which allows to use it within using block, same goes for <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx" rel="nofollow" title="SqlDataReader Class"  target="_blank">SqlDataReader</a> class.</p>
<p>Much faster and secure isn’t it ?</p>
]]></content:encoded>
			<wfw:commentRss>http://ekdd.co.il/howto-properly-connect-to-mssql-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HOWTO: Group rows by day in MSSQL</title>
		<link>http://ekdd.co.il/group-rows-by-day-in-mssql/</link>
		<comments>http://ekdd.co.il/group-rows-by-day-in-mssql/#comments</comments>
		<pubDate>Sun, 13 Sep 2009 13:53:52 +0000</pubDate>
		<dc:creator>eugene</dc:creator>
				<category><![CDATA[MSSQL]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://ekdd.co.il/?p=52</guid>
		<description><![CDATA[This trick is usually useful in statistic where you need to count or sum records based on record day. Using it will help you grouping rows by day or month depends on your needs.
real life example:
My client had an Orders table where online shop orders  were stored while his requirement was to create a graph [...]]]></description>
			<content:encoded><![CDATA[<p><strong>This</strong> trick is usually useful in statistic where you need to count or sum records based on record day. Using it will help you grouping rows by day or month depends on your needs.</p>
<p><span id="more-52"></span><strong>real life example:</strong></p>
<p>My client had an Orders table where online shop orders  were stored while his requirement was to create a graph that will show daily and monthly orders, so the question was how to group dates when order time was different? To convert it to <em>varchar</em> and then to remove time or to just group by <em>day(orderDate),month(orderDate),yeaR(orderDate)</em> ? Way too long, here where this trick came in use for. Basically what it does is gets number of days from zero day inside of <em>datediff </em>function and then adds this amount zero day to get <em>smalldatetime</em> type back. This trick works with days and month just instead of <em>dd</em> call <em>mm</em></p>
<p><strong>code:</strong></p>
<pre class="brush: sql">

select sum(productPrice) as productPrice,

count(productPrice) as numOfProductsSold

from Orders

group by dateadd(dd,datediff(dd,0,orderDate),0)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ekdd.co.il/group-rows-by-day-in-mssql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HOWTO: Schedule MSSQL query task</title>
		<link>http://ekdd.co.il/schedule-mssql-query-task/</link>
		<comments>http://ekdd.co.il/schedule-mssql-query-task/#comments</comments>
		<pubDate>Sat, 12 Sep 2009 17:59:28 +0000</pubDate>
		<dc:creator>eugene</dc:creator>
				<category><![CDATA[MSSQL]]></category>
		<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[sql management]]></category>

		<guid isPermaLink="false">http://ekdd.co.il/?p=38</guid>
		<description><![CDATA[Check the images below to learn how to create a scheduled mssql query task using Microsoft’s Sql Server Management Studio. Red zones are the most important for you to check or to click on and black zones are the ones you not supposed see because screenshots were taken from live server.

real life example:
My client’s community [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Check</strong> the images below to learn how to create a scheduled mssql query task using Microsoft’s Sql Server Management Studio. Red zones are the most important for you to check or to click on and black zones are the ones you not supposed see because screenshots were taken from live server.</p>
<p><span id="more-38"></span></p>
<p><strong>real life example:</strong></p>
<p>My client’s community website had a sql table OnlineUsers where every logged in user was stored on login with time user logged in or moved a page last time which was an indication that user is still online. Previously a trigger to delete inactive users was a login of some other user. So each time other user logged in, he triggered delete statement on table where userLastActivityTime was more than 30 minutes ago. In some situation each minute about 20 users users logged in and at night there were almost none. So i came up with idea to create a scheduled sql task that runs each two minutes and deletes users that made no action in 30 minutes. It reduces number of requests in daytime and made night results more precise. In general it reduces amount of unwanted transactions in x times.</p>
<p><strong>pictures:</strong></p>

<div class="ngg-galleryoverview" id="ngg-gallery-1-38">


	<!-- Piclense link -->
	<div class="piclenselink">
		<a class="piclenselink" href="javascript:PicLensLite.start({feedUrl:'http://ekdd.co.il/wp-content/plugins/nextgen-gallery/xml/media-rss.php?gid=1&amp;mode=gallery'});">
			[View with PicLens]		</a>
	</div>
	
	<!-- Thumbnails -->
		
	<div id="ngg-image-1" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://ekdd.co.il/wp-content/gallery/schedule-mssql-query-task/schedule-mssql-query-task-1.png" title=" " class="shutterset_set_1" >
								<img title="schedule-mssql-query-task-1" alt="schedule-mssql-query-task-1" src="http://ekdd.co.il/wp-content/gallery/schedule-mssql-query-task/thumbs/thumbs_schedule-mssql-query-task-1.png" width="100" height="75" />
							</a>
		</div>
	</div>
	
		
 		
	<div id="ngg-image-2" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://ekdd.co.il/wp-content/gallery/schedule-mssql-query-task/schedule-mssql-query-task-2.png" title=" " class="shutterset_set_1" >
								<img title="schedule-mssql-query-task-2" alt="schedule-mssql-query-task-2" src="http://ekdd.co.il/wp-content/gallery/schedule-mssql-query-task/thumbs/thumbs_schedule-mssql-query-task-2.png" width="100" height="75" />
							</a>
		</div>
	</div>
	
		
 		
	<div id="ngg-image-3" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://ekdd.co.il/wp-content/gallery/schedule-mssql-query-task/schedule-mssql-query-task-3.png" title=" " class="shutterset_set_1" >
								<img title="schedule-mssql-query-task-3" alt="schedule-mssql-query-task-3" src="http://ekdd.co.il/wp-content/gallery/schedule-mssql-query-task/thumbs/thumbs_schedule-mssql-query-task-3.png" width="100" height="75" />
							</a>
		</div>
	</div>
	
		
 		
	<div id="ngg-image-4" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://ekdd.co.il/wp-content/gallery/schedule-mssql-query-task/schedule-mssql-query-task-4.png" title=" " class="shutterset_set_1" >
								<img title="schedule-mssql-query-task-4" alt="schedule-mssql-query-task-4" src="http://ekdd.co.il/wp-content/gallery/schedule-mssql-query-task/thumbs/thumbs_schedule-mssql-query-task-4.png" width="100" height="75" />
							</a>
		</div>
	</div>
	
		
 		
	<div id="ngg-image-5" class="ngg-gallery-thumbnail-box"  >
		<div class="ngg-gallery-thumbnail" >
			<a href="http://ekdd.co.il/wp-content/gallery/schedule-mssql-query-task/schedule-mssql-query-task-5.png" title=" " class="shutterset_set_1" >
								<img title="schedule-mssql-query-task-5" alt="schedule-mssql-query-task-5" src="http://ekdd.co.il/wp-content/gallery/schedule-mssql-query-task/thumbs/thumbs_schedule-mssql-query-task-5.png" width="100" height="75" />
							</a>
		</div>
	</div>
	
		
 	 	
	<!-- Pagination -->
 	<div class='ngg-clear'></div>
 	
</div>


]]></content:encoded>
			<wfw:commentRss>http://ekdd.co.il/schedule-mssql-query-task/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HOWTO: Loop though each query result or MSSQL for loop</title>
		<link>http://ekdd.co.il/loop-though-each-query-results/</link>
		<comments>http://ekdd.co.il/loop-though-each-query-results/#comments</comments>
		<pubDate>Fri, 11 Sep 2009 17:31:41 +0000</pubDate>
		<dc:creator>eugene</dc:creator>
				<category><![CDATA[MSSQL]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://ekdd.co.il/?p=19</guid>
		<description><![CDATA[Many times i found myself in trouble ( Beatles ???) when i needed to change sql tables design based on some conditional logic so i couldn’t use Insert Select technique simply because it doesn’t support if statements when i needed something beyond when condition abilities.

real life example :
problem i faced lately was relationship icons near [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Many</strong> times i found myself in trouble ( Beatles ???) when i needed to change sql tables design based on some conditional logic so i couldn’t use <a href="http://ekdd.co.il/redesign-sql-table-using-insert-select-technique/"title="insert select" >Insert Select technique</a> simply because it doesn’t support <em>if statements</em> when i needed something beyond <em>when condition </em>abilities.</p>
<p><span id="more-19"></span></p>
<p><strong>real life example :</strong></p>
<p>problem i faced lately was relationship icons near each profile for community website when users had a relationships (ie. sent messages), messages were stored in “Messages” table and my requirement was to show near each user’s profile whether logged user had a relationship with them and what kind. So you could say just have a <em>JOIN</em> between “Users” and “Messages” sql tables but first of i had 4 kinds of relationships and second of all think what kind of optimization would it be to have even one <em>JOIN</em> between two tables with more than hundreds of thousands records each. This ain’t working unless you are ready to buy super servers to store databases on. You could also say create a function that checks for each returned from query user what kind of relationship logged user has with which is fine but i this way i would have many double records like UserA and UserB could have messaged each other, added to friend or blacklist.</p>
<p>So the idea was to create a Relationships sql table which holds User1,User2,Relationship1,Relationship2,Relationship3,Relationship4. When any Relationship column was an integer “0” for no relationship, 1 for User1’s action, 2 for User2’s action and 3 for mutual action ( both users messaged each other).</p>
<p>You  can say now cool, this what i should do in the first place but if you work on website optimization like i did? What if you are not the original designer?</p>
<p>Now what ? Problem is that there is a message record for each message sent between users so every time message was sent the sender was User1 and the receiver was User2 which created lots of records for single relationship when i needed create one field  that contains all the relationships between two users. This where for statement comes handy. First of all i created a stored procedure that had a conditional logic, checked if there is a relationship between users and then updated or inserted upon request. Now all i need is a for loop though Messages table so it will send User1 and User2 to my stored procedure, this is where cursors came to save me because otherwise i would be needed to create C# function to make the conditional logic which would be many times slower. Cursors are not advisable for real time results as well simply because they are very slow and CPU demanding compared to more elegant solutions in sql or just proper design but in off-line changes like these i could allow to have cursor for loop but again the are much faster than C# accessing the database and manipulating it.</p>
<p>here is the code</p>
<p><strong>code :</strong></p>
<pre class="brush: sql">
-- setting nocount on so the query will be faster as won&#039;t return number of rows affected
set nocount on
-- declaration of two int variables which will hold current userID&#039;s
declare @userA int, @userB int
--declaration of the cursor that will loop though table in it&#039;s declaration
declare cur cursor for select fieldA,fieldB from tableA
-- opening cursor
open cur
-- get first result from table
fetch next from cur into @userA ,@userB
-- loop until there are no rows left
while @fetch_status = 0
begin
-- stored procedure with current userIDs
exec someStoredProcedure @userA ,@userB
-- get next result
fetch next from cur into @userA ,@userB
end
-- closing cursor
close cur
-- removing it from sql server memory
deallocate cur
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ekdd.co.il/loop-though-each-query-results/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HOWTO: Redesign sql table using Insert Select technique</title>
		<link>http://ekdd.co.il/redesign-sql-table-using-insert-select-technique/</link>
		<comments>http://ekdd.co.il/redesign-sql-table-using-insert-select-technique/#comments</comments>
		<pubDate>Thu, 10 Sep 2009 16:36:19 +0000</pubDate>
		<dc:creator>eugene</dc:creator>
				<category><![CDATA[MSSQL]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://ekdd.co.il/?p=20</guid>
		<description><![CDATA[My requirement was to totally redesign the table when i couldn’t just perform delete and update tasks on it. In this example i create new table based on old table’s filtered result set.

real life example:
My client had a CostumerDeals table with large amount of records in it, each time a costumer logged in to check [...]]]></description>
			<content:encoded><![CDATA[<p><strong>My</strong> requirement was to totally redesign the table when i couldn’t just perform delete and update tasks on it. In this example i create new table based on old table’s filtered result set.</p>
<p><span id="more-20"></span></p>
<p><strong>real life example:</strong></p>
<p>My client had a CostumerDeals table with large amount of records in it, each time a costumer logged in to check his deals this large table was looped though. So my idea was to create a trigger (see <a href="http://ekdd.co.il/schedule-mssql-query-task/">schedule MSSQL query task</a>) that will move (insert into new table and then delete) costumers deals which are older than 6 month to CostumerDeals_old table so the records amount decreased in 90% which made faster responses but also made me to program a trigger for removal of older than 6 month user deal and in case user returns to get his deal records back. It was time consuming but worth it.</p>
<p><strong>code :</strong></p>
<pre class="brush: sql">
use dbName
insert into tableA (colAA,colAB,colAC.....)
select colBA,colBB,colBC.... from tableB where dateadd(mm,6,dealDate)&lt;getdate()
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ekdd.co.il/redesign-sql-table-using-insert-select-technique/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
