<?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>The Art of Software &#187; SQL Server</title>
	<atom:link href="http://orionseven.com/blog/tag/sql-server/feed/" rel="self" type="application/rss+xml" />
	<link>http://orionseven.com/blog</link>
	<description>It takes a lot more than code to make software.</description>
	<lastBuildDate>Fri, 23 Jul 2010 21:00:49 +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>T-SQL Tuesday: Spot Relationship&#8217;s with Database Diagrams</title>
		<link>http://orionseven.com/blog/2010/02/08/t-sql-tuesday-spot-relationships-with-database-diagrams/</link>
		<comments>http://orionseven.com/blog/2010/02/08/t-sql-tuesday-spot-relationships-with-database-diagrams/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 05:25:56 +0000</pubDate>
		<dc:creator>Bryan Smith</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[T-SQL Tuesday]]></category>
		<category><![CDATA[Foreign Keys]]></category>
		<category><![CDATA[Relational Database]]></category>

		<guid isPermaLink="false">http://orionseven.com/blog/?p=91</guid>
		<description><![CDATA[As part of this months  T-SQL Tuesday on &#8220;relationships&#8221; I thought I&#8217;d post about a handy feature in SQL Server Management Studio.
As the title of the article implies I&#8217;m going to discuss how database diagrams in SSMS can be handy to visually see the relationship&#8217;s in a database. But I think I could have also [...]]]></description>
			<content:encoded><![CDATA[<p>As part of this months  <a href="http://msmvps.com/blogs/robfarley/archive/2010/02/02/invitation-for-t-sql-tuesday-003-relationships.aspx">T-SQL Tuesday</a> on &#8220;relationships&#8221; I thought I&#8217;d post about a handy feature in SQL Server Management Studio.</p>
<p>As the title of the article implies I&#8217;m going to discuss how database diagrams in SSMS can be handy to visually see the relationship&#8217;s in a database. But I think I could have also named the article &#8220;T-SQL Tuesday: Spot Relationship&#8217;s with Database Diagrams, or the Lack of Them&#8221;.</p>
<p>Out of the box and with a deployed database you may get a warning about trying to use a database diagram and that they&#8217;re not accessible. Quite often this is because the database does not have a valid owner. As always Books Online is our hero, you can <a href="http://msdn.microsoft.com/en-us/library/ms178630.aspx">use sp_changedbowner to change the owner</a>. While you&#8217;re at BoL <a href="http://msdn.microsoft.com/en-us/library/ms186345.aspx">read this too, it explains database diagram ownership</a>.</p>
<p>With that out of the way we can move on to the point of this article. Relationships!</p>
<p>SSMS&#8217;s database diagram&#8217;s when first made will ask you what tables you want to add to the diagram. Go ahead and add them all, you&#8217;ll end up with a nicely formatted diagram showing you your tables all lined up nicely with each other. Your results will vary but will likely be a mixture of the tables neatly arrayed with lines drawn between them &#8230; or &#8230; tables neatly arrayed one after another after another with nary a line to be seen. As they say, &#8220;Hope for the best but prepare for the worst.&#8221;</p>
<p>If you&#8217;re lucky and you have lines between tables rest assured that at least some tables have foreign keys between tables. But don&#8217;t rest too long because just because there are lines doesn&#8217;t mean there are enough of them (or there might be too many). It&#8217;s now time to look at each table neatly arrayed and familiarize yourself with the schema. I find that visually it is quite easy this way to spot likely candidates for FK&#8217;s. You&#8217;re also likely to spot other things, such as PK candidates, better normalization strategies, moments of sheer database schema genius, or pure database depravity. If you find the latter then&#8230;</p>
<p>Database diagrams are also great for spotting everything that&#8217;s missing as well. Orphaned tables are quite obvious sitting all by themselves, and again I find it visually easy to quickly tell if that&#8217;s the way it should be or shouldn&#8217;t be. If you find everything is missing you can start adding FK&#8217;s right there in your diagram. Simply right click on a table and you&#8217;re given quite a few options to start updating your schema. (See the warning below!)</p>
<p>Anyhow, I hope everyone gives SSMS&#8217;s diagrams a try. It does not replace sitting down and verifying your database&#8217;s relationship&#8217;s one by one. But it does make a great aid in doing so.</p>
<p>A couple of additional points to keep in mind when looking using database diagrams:</p>
<ul>
<li>Remember there are times you might not want a foreign key. FK&#8217;s do imply overhead and in a performance consideration there may be a valid reason to not have them.</li>
<li>The diagram resizing isn&#8217;t really all that great, 75% means that the text is 25% less legible. Not very handy unless you want to get a REALLY high level view.</li>
<li>Go ahead and drag things around. I do all the time.</li>
<li>Try printing these out! Print to a PDF with something like CutePDF or if you&#8217;re lucky like I am with a large format printer print it out on a 3&#8242; x 3&#8242; piece of paper and start drawing all over it.</li>
</ul>
<p>And finally a word of warning!</p>
<p>The changes you make in a database diagram can be committed! So don&#8217;t go trying to drop database objects in a production environment. I think it&#8217;s best practice to just not use them in production. Unless you&#8217;ve practiced your disaster recovery recently and feel quite confident in it.</p>
]]></content:encoded>
			<wfw:commentRss>http://orionseven.com/blog/2010/02/08/t-sql-tuesday-spot-relationships-with-database-diagrams/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Using Table-Valued Parameters in SQL Server 2008 and C#</title>
		<link>http://orionseven.com/blog/2009/09/30/using-table-valued-parameters-in-sql-server-2008-and-c/</link>
		<comments>http://orionseven.com/blog/2009/09/30/using-table-valued-parameters-in-sql-server-2008-and-c/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 20:28:22 +0000</pubDate>
		<dc:creator>Bryan Smith</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://orionseven.com/blog/?p=20</guid>
		<description><![CDATA[Until recently I had not had an opportunity to use Table-Valued Parameters a new feature in SQL Server 2008. I had looked at them briefly, thought they were a nice addition, and then moved on. Finally though, I found a chance to use them.
The intended use for Table-Valued Parameters is of course to send multiple [...]]]></description>
			<content:encoded><![CDATA[<p>Until recently I had not had an opportunity to use <a href="http://msdn.microsoft.com/en-us/library/bb510489.aspx">Table-Valued Parameters</a> a new feature in SQL Server 2008. I had looked at them briefly, thought they were a nice addition, and then moved on. Finally though, I found a chance to use them.</p>
<p>The intended use for Table-Valued Parameters is of course to send multiple rows of data to SQL Server from the client. Previous ways to do this involved calling a single stored procedure repeatedly, using XML, using SQLBulkCopy, or my least favorite, creating a stored procedure with many parameters. Each of these methods had draw backs. Calling a single stored procedure over and over works just fine (and was my preferred method) but you are creating a lot of traffic for something that should be simple. XML was nice too, but depending on the complexity of what you are sending you will need a lot of XQuery in your stored procedure; making something simple much more complex. SQLBulkCopy works great, I’ve used it before, but sometimes you may want to do more to your data once it is at the database. Thankfully table-valued parameters solve many of these short comings.</p>
<p>You can use table-valued parameters from your application with DataTables, DbDataReader, or IEnumerable objects. The majority of examples for table-valued parameters are done using DataTables. The problem I have with DataTables is that this seems like too much of an ad-hoc method with more overhead then is needed. Whereas going the IEnumerable route lets you create and use objects that you would likely already be using. This is the route I prefer, and the one I will demonstrate.</p>
<p>For this example assume we have a database of people and each of the people may have one or more aliases. They must be rather shady people. Here is the table for storing the people:</p>
<blockquote>
<pre>CREATE TABLE tbl_Person
(
      [ID] INT IDENTITY(1,1) NOT NULL,
      [FirstName] VARCHAR(20) NOT NULL,
      [LastName] VARCHAR(20) NOT NULL
)</pre>
</blockquote>
<p>It is quite simple, an identity field called ID to give everyone a unique number and a first and last name.</p>
<p>Now we have a table to store their aliases:</p>
<blockquote>
<pre>CREATE TABLE tbl_Alias
(
      [ID] INT NOT NULL,
      [FirstName] VARCHAR(20) NOT NULL,
      [LastName] VARCHAR(20) NULL
)</pre>
</blockquote>
<p>Another simple table to keep our shady people’s aliases; let’s pretend for ease of use there are primary keys and foreign keys shall we?</p>
<p>To add to this table we will use a stored procedure, my favorite mechanism to get data to the database. Why? Because you give the DBA something concrete upon which they can optimize your database, among other reasons. But that’s another post.</p>
<p>Our stored procedure will be an inserting stored procedure which will add our new shady person and their aliases in one call. Thus we will need to<a href="http://msdn.microsoft.com/en-us/library/ms175007.aspx"> create our user-defined table type</a>  first.</p>
<blockquote>
<pre>CREATE TYPE udt_tbl_Alias AS TABLE
(
      [FirstName] VARCHAR(20) NOT NULL,
      [LastName] VARCHAR(20) NULL
)</pre>
</blockquote>
<p>Again, nothing complicated. You will see why I left off the ID field in a bit.</p>
<p>You should note that you cannot use ALTER commands on user-defined table types. So if you want to update the table type later you will have drop it and create it. But if it is being used by a stored procedure you will have to temporarily comment that out of your stored procedure first, then drop the UDT, create the UDT again, and uncomment the UDT in your stored procedure. So plan ahead! Having planned ahead, here is our stored procedure for inserting:</p>
<blockquote>
<pre>CREATE PROCEDURE usp_ins_Person
      @FirstName VARCHAR(20),
      @LastName VARCHAR(20),
      @Aliases udt_tbl_Alias READONLY
AS
BEGIN
      SET NOCOUNT ON

      INSERT INTO tbl_Person VALUES (@FirstName, @LastName)

      INSERT INTO tbl_Alias (ID, FirstName, LastName)
            SELECT @@IDENTITY [ID], FirstName, LastName FROM @Aliases
END</pre>
</blockquote>
<p>The stored procedure requires three parameters: a first name, a last name and the user-defined table-valued parameter. The table type must be marked as READONLY and thus you will not be able to update the table within the stored procedure, only select from it. Otherwise, the stored procedure is rather straight forward. The person is added to tbl_Person and the aliases are added to tbl_Alias. You can see why I chose not to have the ID part of the user-defined table type, since we will not the ID till the person has been inserted.</p>
<p>To use the stored procedure in SQL Server Management Studio you can do the following.</p>
<blockquote>
<pre>DECLARE @Aliases udt_tbl_Alias
DECLARE @FirstName VARCHAR(20) = 'Bryan'
DECLARE @LastName VARCHAR(20) = 'Smith'
 
INSERT INTO @Aliases VALUES ('Database', 'Guy'), ('DBA', NULL)
 
EXEC usp_ins_Person @FirstName, @LastName, @Aliases
 
SELECT * FROM tbl_Person
SELECT * FROM tbl_Alias</pre>
</blockquote>
<p>The output should look like this.</p>
<div id="attachment_19" class="wp-caption alignnone" style="width: 203px"><img class="size-full wp-image-19" title="udt_output" src="http://orionseven.com/blog/wp-content/uploads/2009/09/udt_output.png" alt="Output" width="193" height="139" /><p class="wp-caption-text">Output</p></div>
<p>Great, we’re halfway there! The database side of things is taken care of, now we will need to take care of our client. Within the client code we will create a Person class. The class will have a property for the first name, last name, and aliases. This is why I like the IEnumerable route; it makes sense to store the aliases for a person with the person, and doing so as a list makes sense.</p>
<p>Person Class:</p>
<blockquote>
<pre>
namespace TestUDTApplication
{
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public AliasCollection Aliases { get; set; }
 
        public Person(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
            Aliases = new AliasCollection();
        }
    }
}</pre>
</blockquote>
<p>Alias Class:</p>
<blockquote>
<pre>
namespace TestUDTApplication
{
    class Alias
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
 
        public Alias(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }
    }
}</pre>
</blockquote>
<p>AliasCollection Class:</p>
<blockquote>
<pre>
using System.Collections.Generic;
using System.Data;
using Microsoft.SqlServer.Server;
 
namespace TestUDTApplication
{
    class AliasCollection : List&lt;Alias&gt;, IEnumerable&lt;SqlDataRecord&gt;
    {
        IEnumerator&lt;SqlDataRecord&gt; IEnumerable&lt;SqlDataRecord&gt;.GetEnumerator()
        {
            SqlDataRecord ret = new SqlDataRecord(
                new SqlMetaData("FirstName", SqlDbType.VarChar, 20),
                new SqlMetaData("LastName", SqlDbType.VarChar, 20)
                );
 
            foreach (Alias alias in this)
            {
                ret.SetString(0, alias.FirstName);
                ret.SetString(1, alias.LastName);
                yield return ret;
            }
        }
    }
}</pre>
</blockquote>
<p>Let’s look over this code. First off the Person class has three public properties. FirstName, LastName, and Aliases. The Aliases property is an instance of the AliasCollection class, which inherits the Alias class as a List and then implements the IEnumerable interface. The List&lt;Alias&gt; turns our Alias into a List, which is perfect for handling our aliases within the client code.</p>
<p>The implementation IEnumerable&lt;SqlDataRecord&gt; is what will let us use our List as the input to our user-defined table. Specifically we are implementing IEnumerable with <a href="http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.server.sqldatarecord.aspx">SqlDataRecord</a>, this represents a single row of data and its associated metadata. This is what ADO.Net and SQL Server will need to map our list of aliases to our user-defined table. The <a href="http://msdn.microsoft.com/en-us/library/bb675163.aspx">documentation</a> is not really clear on this part unfortunately, it leads you to believe that anything that implements IEnumerable should suffice, however; what you must have is IEnumerable with SqlDataReader. This does not come out of the box with List&lt;Alias&gt; so we create our own, otherwise we’ll get an InvalidCastException.</p>
<p>Finally, from our client, using the <a href="http://msdn.microsoft.com/en-us/library/cc467894.aspx">Enterprise Library Data Access</a>, we can load people and aliases using a user-defined table type.</p>
<blockquote>
<pre>
Person person = new Person("Bryan", "Smith");
person.Aliases.Add(new Alias("DBA", "Dude"));
person.Aliases.Add(new Alias("Database", "Guy"));
 
SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase("UDTTest");
DbCommand cmd = db.GetStoredProcCommand("usp_ins_Person");
 
db.AddInParameter(cmd, "@FirstName", DbType.String, person.FirstName);
db.AddInParameter(cmd, "@LastName", DbType.String, person.LastName);
db.AddInParameter(cmd, "@Aliases", SqlDbType.Structured, person.Aliases);
 
db.ExecuteNonQuery(cmd);</pre>
</blockquote>
<p>I know personally, I’ll be using this method from now one whenever possible over using user-defined tables with ad-hoc DataTables to load data, or heaven forbid calling the same stored procedure repeatedly.</p>
]]></content:encoded>
			<wfw:commentRss>http://orionseven.com/blog/2009/09/30/using-table-valued-parameters-in-sql-server-2008-and-c/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
