<?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>Chris Fulstow &#187; sql server</title>
	<atom:link href="http://chrisfulstow.com/category/sql-server/feed/" rel="self" type="application/rss+xml" />
	<link>http://chrisfulstow.com</link>
	<description>ASP.NET Tech Lead and Web Developer</description>
	<lastBuildDate>Sat, 05 Jun 2010 01:32:55 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Installing ASP.NET Membership, Roles and Profiles support in SQL Server</title>
		<link>http://chrisfulstow.com/installing-asp-net-membership-roles-and-profiles-support-in-sql-server/</link>
		<comments>http://chrisfulstow.com/installing-asp-net-membership-roles-and-profiles-support-in-sql-server/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 23:32:19 +0000</pubDate>
		<dc:creator>Chris Fulstow</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[sql server]]></category>

		<guid isPermaLink="false">http://chrisfulstow.com/?p=260</guid>
		<description><![CDATA[Here are few quick tips if you&#8217;re using the ASP.NET Application Services with SQL Server, like Membership, Roles, Profiles, Personalization or Web Events.  These built-in &#8220;building-block&#8221; services have SQL provider implementations in .NET that let you use a SQL Server 2000 or 2005 database as their data store. These are the framework classes that implement <a href="http://chrisfulstow.com/installing-asp-net-membership-roles-and-profiles-support-in-sql-server/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>Here are few quick tips if you&#8217;re using the ASP.NET Application Services with SQL Server, like Membership, Roles, Profiles, Personalization or Web Events.  These built-in &#8220;building-block&#8221; services have SQL <a href="http://msdn2.microsoft.com/en-us/library/ms972319.aspx">provider</a> implementations in .NET that let you use a SQL Server 2000 or 2005 database as their data store. These are the framework classes that implement the SQL Server providers:</p>
<ul>
<li><a href="http://msdn2.microsoft.com/en- us/library/89hwy0w9(VS.80).aspx">SqlMembershipProvider</a> &#8211; managing user credentials and authentication</li>
<li><a href="http://msdn2.microsoft.com/en- us/library/daxt91e3(VS.80).aspx">SqlRoleProvider</a> &#8211; handling role-based authorisation</li>
<li><a href="http://msdn2.microsoft.com/en- us/library/8226cz6c(VS.80).aspx">SqlProfileProvider</a> &#8211; storing and retrieving information about individual users</li>
<li><a href="http://msdn2.microsoft.com/en-us/library/ttfyw56h (VS.80).aspx">SqlPersonalizationProvider</a> &#8211; saving state of web parts</li>
<li><a href="http://msdn2.microsoft.com/en-us/library/axa250f0 (VS.80).aspx">SqlWebEventProvider</a> &#8211; capturing and logging web event data</li>
</ul>
<h2>ASP.NET SQL Server Registration Tool</h2>
<p>Adding support for these providers to your database is easy, just run the <a href="http://msdn2.microsoft.com/en-us/library/ms229862(VS.80).aspx">ASP.NET SQL Server Registration tool</a> from the command-line (aspnet_regsql.exe) to launch the ASP.NET SQL Server Setup Wizard.  This will guide you through the process with a simple GUI:</p>
<pre>cd C:\Windows\Microsoft.NET\Framework\v2.0.50727 aspnet_regsql.exe</pre>
<p>By default, the wizard installs all five <a href="http://www.stockindex500.org">services </a>: Membership, Roles, Profiles, Personalization and Web Events. However, if you need support for only some, say just Membership and Roles, then aspnet_regsql can be run from the command-line with specific options, for example:</p>
<pre> aspnet_regsql -S MySqlServer -E -A mr -d MyAspDatabase</pre>
<p>This installs the Membership and Roles services (-A <strong>mr</strong>) on server <em>MySqlServer</em> in database <em>MyAspDatabase</em> using current Windows credentials for authentication.  To see a full list of command-line options and switches, run the registration tool with the help flag:</p>
<pre> aspnet_regsql.exe /?</pre>
<p>There&#8217;s also an option to generate just SQL scripts without executing them, and another to remove services from the database that aren&#8217;t used or needed anymore. (You can also manage SQL cache dependencies and session state using this tool.)</p>
<p>For more info about ASP.NET SQL providers:</p>
<ul>
<li><a href="http://www.microsoft.com/downloads/details.aspx? FamilyID=b6b5401a-19ea-4262-ba2b-db26f35d09e0&amp;displaylang=en">MSDN &#8211; ASP.NET</a><a href="http://www.microsoft.com/downloads/details.aspx? FamilyID=b6b5401a-19ea-4262-ba2b-db26f35d09e0&amp;displaylang=en"> Provider Model (PDF)</a></li>
<li><a href="http://www.asp.net/learn/videos/video-148.aspx">Video &#8211; How Do</a><a href="http://www.asp.net/learn/videos/video-148.aspx"> I: Set Up the SQL Membership Provider</a></li>
<li><a href="http://weblogs.asp.net/scottgu/archive/2005/08/25/423703.aspx">Configuring</a><a href="http://weblogs.asp.net/scottgu/archive/2005/08/25/423703.aspx"> ASP.NET 2.0 Application Services to use SQL Server 2000 or SQL Server 2005</a></li>
<li><a href="http://aspnet.4guysfromrolla.com/articles/120705- 1.aspx">Examining ASP.NET 2.0&#8217;s Membership, Roles, and Profile</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://chrisfulstow.com/installing-asp-net-membership-roles-and-profiles-support-in-sql-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL Server 2008 will have IntelliSense</title>
		<link>http://chrisfulstow.com/sql-server-2008-will-have-intellisense/</link>
		<comments>http://chrisfulstow.com/sql-server-2008-will-have-intellisense/#comments</comments>
		<pubDate>Fri, 30 Nov 2007 02:59:36 +0000</pubDate>
		<dc:creator>Chris Fulstow</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[sql server 2008]]></category>

		<guid isPermaLink="false">http://3poundmass.wordpress.com/2007/11/30/sql-server-2008-will-have-intellisense/</guid>
		<description><![CDATA[With so many exciting new features in Visual Studio 2008 to explore, I haven&#8217;t had much time to look at the preview releases of SQL Server 2008 (aka Katmai).  The last I heard, there wouldn&#8217;t be that many new goodies for developers, mainly features for DBAs and BI analysts with a few performance optimisations <a href="http://chrisfulstow.com/sql-server-2008-will-have-intellisense/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>With so many exciting <a href="http://weblogs.asp.net/scottgu/archive/2007/11/19/visual-studio-2008-and-net-3-5-released.aspx">new features in Visual Studio 2008</a> to explore, I haven&#8217;t had much time to look at the preview releases of <strong>SQL Server 2008</strong> (aka <em>Katmai</em>).  The last I heard, there wouldn&#8217;t be that many new goodies for developers, mainly features for <strong>DBAs</strong> and <strong>BI analysts</strong> with a few performance optimisations thrown in.</p>
<p>The last upgrade, SQL Server 2000 to 2005, was a huge leap forward for developers and added <strong>significant advances</strong> like CLR integration, SQL Server Management Objects (SMO), Integration Services (SSIS) and a native XML data type; as well as T-SQL enhancements like Common Table Expressions (CTEs), structured error handling with try/catch, pivot, apply, top(n) and row_number.</p>
<p>I was surprised to see how much new stuff is packed into the latest <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=3BF4C5CA-B905-4EBC-8901-1D4C1D1DA884&amp;displaylang=en">SQL Server 2008 CTP release</a>, even, finally, <strong>IntelliSense for Management Studio</strong>, which was much anticipated but conspicuously absent from SQL 2005:</p>
<p><a title="SQL Server 2008 IntelliSense" href="http://chrisfulstow.com/wp-content/uploads/2007/11/sql2008-intellisense.png"><img src="http://chrisfulstow.com/wp-content/uploads/2007/11/sql2008-intellisense.png" alt="SQL Server 2008 IntelliSense" /></a></p>
<p>Also notice the new <strong>collapsible code regions</strong>, just like you get in Visual Studio.  Editing T-SQL has never been such fun!  Although, you have to feel a bit sorry for RedGate, whose <a href="http://www.red-gate.com/products/sql_prompt/index.htm">SQL Prompt</a> plug-in has been filling the auto-completion gap for the last few years.</p>
]]></content:encoded>
			<wfw:commentRss>http://chrisfulstow.com/sql-server-2008-will-have-intellisense/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Finding orphaned stored procedures and user-defined functions in SQL Server</title>
		<link>http://chrisfulstow.com/finding-orphaned-stored-procedures-and-user-defined-functions-in-sql-server/</link>
		<comments>http://chrisfulstow.com/finding-orphaned-stored-procedures-and-user-defined-functions-in-sql-server/#comments</comments>
		<pubDate>Thu, 22 Nov 2007 02:49:14 +0000</pubDate>
		<dc:creator>Chris Fulstow</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://3poundmass.wordpress.com/2007/11/22/finding-orphaned-stored-procedures-and-user-defined-functions-in-sql-server/</guid>
		<description><![CDATA[I&#8217;m currently working on a group of ASP.NET 2.0 websites deployed across about thirty countries.  The local flagship site runs on an upgraded version of the original code, and I&#8217;m now in the process of bringing all the other sites onto the new improved version.
Over time, new features have been introduced to the site, <a href="http://chrisfulstow.com/finding-orphaned-stored-procedures-and-user-defined-functions-in-sql-server/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently working on a group of <strong>ASP.NET 2.0 websites</strong> deployed across about <strong>thirty countries</strong>.  The local flagship site runs on an upgraded version of the original code, and I&#8217;m now in the process of bringing all the other sites onto the new improved version.</p>
<p>Over time, new features have been introduced to the site, and old ones removed.  Consequently the <strong>SQL Server database</strong> now contains many <strong>redundant tables</strong> that aren&#8217;t used.  So, before cascading out the current schema to the other countries, it&#8217;s time for a clean up.</p>
<p>I managed to identify about 60 tables that aren&#8217;t used by the application and can safely can be dropped or archived.  However, I&#8217;m now left with <strong>hundreds of stored procedures</strong> (SPs) and user-defined functions (UDFs) that were associated with these tables, which can also be removed.</p>
<p>The problem was how to find these <strong>orphaned objects</strong>.  My first approach was a small .NET <strong>console application </strong>which uses <a href="http://technet.microsoft.com/en-us/library/ms162169.aspx">SQL Server Management Objects</a> (SMO).  It loops through all SPs and UDFs and finds any that have <strong>no dependencies</strong>.</p>
<pre class="brush: csharp;">

public List&lt;string&gt; FindOrphans()
{
   Server server = new Server(&quot;.&quot;);
   Database db = server.Databases[&quot;MyDatabase&quot;];
   List&lt;string&gt; orphans = new List&lt;string&gt;();

   // get list of SPs
   UrnCollection urns = new UrnCollection();
   foreach (StoredProcedure sp in db.StoredProcedures)
   {
      // exclude these objects
      if (sp.IsSystemObject) continue;
      if (sp.Name.StartsWith(&quot;aspnet_&quot;)) continue;
      urns.Add(sp.Urn);
   }

   // get dependencies
   DependencyWalker dw = new DependencyWalker(server);
   DependencyTree tree = dw.DiscoverDependencies(urns, true);

   // find all objects without any dependencies
   DependencyTreeNode node = tree.FirstChild;
   do {
      if (!node.HasChildNodes)
      {
         string name = new Urn(node.Urn).GetAttribute(&quot;Name&quot;);
         orphans.Add(name);
      }
      node = node.NextSibling;
   } while (node != null);

   return orphans;
}
</pre>
<p>This works fine, and helped satisfy my current obsession with SMO.  But it&#8217;s a bit awkward, and not easily <strong>portable or modifiable</strong>, to have this pure database operation wrapped up in an executable.  So I looked into doing the same thing with just a <strong>TSQL query</strong>.</p>
<pre class="brush: sql;">
-- Find all SPs and UDFs have no dependencies
select
    object_name(obj.[object_id]) as [orphaned_object_name],
    obj.type_desc as [object_type],
    'DROP ' +
    case obj.type_desc
        when 'SQL_STORED_PROCEDURE' then 'PROCEDURE'
        else 'FUNCTION'
    end
    + ' [' + object_name(obj.[object_id]) + ']'
from
    sys.objects obj
    left join (select distinct [object_id] from sys.sql_dependencies) dep
        on obj.object_id = dep.object_id
where
    type_desc in
        ('SQL_STORED_PROCEDURE','SQL_SCALAR_FUNCTION','SQL_TABLE_VALUED_FUNCTION')
    and object_name(obj.[object_id]) not like 'aspnet_%'
    and dep.object_id is null
order by
    obj.type_desc, object_name(obj.[object_id])
</pre>
<p>The query works by checking for dependencies in the <strong>catalog view</strong> <a href="http://msdn2.microsoft.com/en-us/library/ms174402.aspx">sys.sql_dependencies</a>.  This, I think, is a neater solution.  I also included an <strong>auto-generated column</strong> that writes the SQL drop the SP or UDF, which I copied and executed.</p>
<p>Now, if only I could find a quick way to check for dependencies between my application&#8217;s <strong>data access layer </strong>and the database&#8230;</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2f3poundmass.wordpress.com%2f2007%2f11%2f22%2ffinding-orphaned-stored-procedures-and-user-defined-functions-in-sql-server%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2f3poundmass.wordpress.com%2f2007%2f11%2f22%2ffinding-orphaned-stored-procedures-and-user-defined-functions-in-sql-server%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://chrisfulstow.com/finding-orphaned-stored-procedures-and-user-defined-functions-in-sql-server/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Convert table to CSV string in SQL Server</title>
		<link>http://chrisfulstow.com/convert-table-to-csv-string-in-sql-server/</link>
		<comments>http://chrisfulstow.com/convert-table-to-csv-string-in-sql-server/#comments</comments>
		<pubDate>Wed, 22 Aug 2007 03:20:45 +0000</pubDate>
		<dc:creator>Chris Fulstow</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[sql server]]></category>

		<guid isPermaLink="false">http://3poundmass.wordpress.com/2007/08/22/convert-table-to-csv-string-in-sql-server/</guid>
		<description><![CDATA[There doesn&#8217;t seem to be a native function in SQL Server to collapse a table of row values into a comma-separated string, for example:
Animal
Llama
Manatee
Pygmy Marmoset
Okapi
Result CSV: &#8220;Llama, Manatee, Pygmy Marmoset, Okapi&#8221;
In mySQL there&#8217;s a built-in aggregate function called group_concat, but no equivalent in SQL Server unless you build your own .NET function, like in this <a href="http://chrisfulstow.com/convert-table-to-csv-string-in-sql-server/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>There doesn&#8217;t seem to be a native function in <strong>SQL Server</strong> to collapse a table of row values into a comma-separated string, for example:</p>
<p><strong><u>Animal</u></strong><br />
Llama<br />
Manatee<br />
Pygmy Marmoset<br />
Okapi</p>
<p><strong>Result CSV:</strong> &#8220;Llama, Manatee, Pygmy Marmoset, Okapi&#8221;</p>
<p>In <a href="http://www.mysql.com/">mySQL</a> there&#8217;s a built-in aggregate function called <a href="http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat">group_concat</a>, but no equivalent in SQL Server unless you build your own .NET function, like in this TechNet article <a href="http://technet.microsoft.com/en-us/library/ms131056.aspx">Invoking CLR User-Defined Aggregate Functions</a>.  That&#8217;s quite a chunk of coding and is restricted to SQL Server 2005 or later, so here&#8217;s a handy SQL snippet that does a similar job without the fuss.</p>
<p><span style="color:blue;">select</span> Name <span style="color:blue;">from</span> Animal</p>
<p><span style="color:blue;">declare</span> @csv <span style="color:blue;">varchar</span>(<span style="color:magenta;">max</span>)<br />
<span style="color:blue;">select</span> @csv = <span style="color:magenta;">coalesce</span>(@csv + &#8216;, &#8216;, &#8221;) + Name <span style="color:blue;">from</span> Animal<br />
<span style="color:blue;">select</span> @csv</p>
<p>If you use the code regularly then consider creating a <a href="http://technet.microsoft.com/en-us/library/ms177499.aspx">scalar user-defined function</a> (UDF) that returns the <strong>CSV</strong> string as varchar.</p>
]]></content:encoded>
			<wfw:commentRss>http://chrisfulstow.com/convert-table-to-csv-string-in-sql-server/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>.NET Coding Guidelines &#8211; SQL Injection</title>
		<link>http://chrisfulstow.com/coding-guidelines-sql-injection/</link>
		<comments>http://chrisfulstow.com/coding-guidelines-sql-injection/#comments</comments>
		<pubDate>Fri, 03 Aug 2007 00:05:13 +0000</pubDate>
		<dc:creator>Chris Fulstow</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[vb.net]]></category>

		<guid isPermaLink="false">http://3poundmass.wordpress.com/2007/08/03/coding-guidelines-sql-injection/</guid>
		<description><![CDATA[In the first of my guidelines for deadbeat developers, I asked why you&#8217;re too lazy to comment your code.  This time, I&#8217;d like to investigate why you build software that&#8217;s catastrophically insecure.
Part 2 &#8211; Protect against SQL injection in .NET
This code will look familiar because it&#8217;s the sort of sloppy mistake you make all <a href="http://chrisfulstow.com/coding-guidelines-sql-injection/" class="more-link">More &#62;</a>]]></description>
			<content:encoded><![CDATA[<p>In the first of my guidelines for deadbeat developers, I asked why you&#8217;re too lazy to <a href="/2007/07/26/coding-guidelines-commenting/">comment your code</a>.  This time, I&#8217;d like to investigate why you build software that&#8217;s catastrophically insecure.</p>
<h2>Part 2 &#8211; Protect against SQL injection in .NET</h2>
<p>This code will look familiar because it&#8217;s the sort of sloppy mistake you make all the time.</p>
<pre><span style="color:blue;">string</span> productId = Request.QueryString[<span style="color:#a31515;">"ProductId"</span>];
<span style="color:blue;">string</span> sql = <span style="color:#a31515;">"delete Products where Id="</span> + productId;
<span style="color:#2b91af;">SqlCommand</span> cmd = <span style="color:blue;">new</span> <span style="color:#2b91af;">SqlCommand</span>(sql);
cmd.ExecuteNonQuery();</pre>
<p>Your feeble imagination doesn&#8217;t stretch far enough to consider what happens when a mischievous user sets productId to, say, &#8220;1 OR 1=1&#8243;.  You merrily build the query, complete with unverified user input, and execute it against the database.</p>
<pre><span style="color:blue;">delete</span> Products <span style="color:blue;">where</span> Id=1 <span style="color:blue;">OR</span> 1=1</pre>
<p>Oh dear, where did all your products go?</p>
<p>A vigilant SQL Server DBA can thwart your stupidity at the database by restricting your access.  By assigning your login to the <a href="http://msdn2.microsoft.com/en-us/library/ms187916.aspx" target="_blank">db_denydatareader</a> and <a href="http://msdn2.microsoft.com/en-us/library/ms188308.aspx" target="_blank">db_denydatawriter</a> roles, you can thankfully be prevented from running any SELECT, DELETE, INSERT or UPDATE queries whatsoever.</p>
<p><img src="http://3poundmass.files.wordpress.com/2007/07/denied.png" alt="SQL Server roles" /></p>
<p>Since you can&#8217;t be trusted, the DBA should give you permissions to execute only the stored-procedures and UDFs you need.  This is the <a href="http://en.wikipedia.org/wiki/Principle_of_least_privilege">principle of least privilege</a>.</p>
<p><img src="http://3poundmass.files.wordpress.com/2007/07/grant-exec1.png" alt="Grant SQL exec permission" /></p>
<p>Parameterised stored-procedures are usually safe from SQL injection because they validate the type and size of the inputs.  These inputs are evaluated as values only, and not executed as part of the SQL statement.  But there is one exception.  When you build SQL dynamically inside the stored-procedure.</p>
<p><span style="color:darkred;">sp_executesql</span> <span style="color:red;">&#8217;select * from Products where Id in &#8216;</span> + @List</p>
<p>This line is from a real stored-procedure I saw last week, @List is a varchar parameter containing something like &#8220;(1,2,3)&#8221;. <span style="color:darkred;"></span>And, of course, the values for @List came from unverified user input.  If you absolutely have to use dynamic SQL then at least clean the inputs and remove or escape anything that could be potentially dangerous.</p>
<p><strong>Read more about SQL injection:</strong></p>
<ul>
<li><a href="http://msdn2.microsoft.com/en-us/library/ms998271.aspx">How To: Protect From SQL Injection in ASP.NET</a></li>
<li><a href="http://msdn2.microsoft.com/en-us/library/ms161953.aspx">SQL Server BOL: SQL Injection</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://chrisfulstow.com/coding-guidelines-sql-injection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
