<?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>Quickduck &#187; Sql Server</title> <atom:link href="http://quickduck.com/blog/category/development/sql-server/feed/" rel="self" type="application/rss+xml" /><link>http://quickduck.com/blog</link> <description>Straight from the mind of geniuseseses....</description> <lastBuildDate>Mon, 09 Jan 2012 02:29:30 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <item><title>Varchar, Nvarchar and Entity Framework</title><link>http://quickduck.com/blog/2010/09/23/varchar-nvarchar-and-entity-framework/</link> <comments>http://quickduck.com/blog/2010/09/23/varchar-nvarchar-and-entity-framework/#comments</comments> <pubDate>Thu, 23 Sep 2010 01:41:29 +0000</pubDate> <dc:creator>Drew Freyling</dc:creator> <category><![CDATA[.Net]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Sql Server]]></category> <category><![CDATA[Data Access]]></category> <category><![CDATA[Performance]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=322</guid> <description><![CDATA[Further to my previous post about a bug with Entity Framework 1.0, I&#8217;ve have discovered another bug but this time due to its handling of varchars. Let&#8217;s assume we&#8217;re using the following query: If our Country column is a varchar Entity Framework will pass through our &#8220;Australia&#8221; string as an nvarchar parameter regardless of what [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2010/09/23/varchar-nvarchar-and-entity-framework/"></g:plusone></div><p>Further to my <a href="http://quickduck.com/blog/2010/04/24/handling-of-nulls-in-entity-framework/">previous post</a> about a bug with Entity Framework 1.0, I&#8217;ve have discovered another bug but this time due to its handling of varchars.</p><p>Let&#8217;s assume we&#8217;re using the following query:</p><pre class="brush: plain; title: ; notranslate">
var query = context.Orders.Where(o =&gt; o.Customer.Address.Country == &quot;Australia&quot;);
</pre><p>If our Country column is a varchar  Entity Framework will pass through our &#8220;Australia&#8221; string as an nvarchar parameter regardless of what we define in our SSDL!<br /> Now has is this a bad thing you may ask? Well what this means is that even if we have an index on our country column, SQL Server will have to do an index scan rather than an index seek because it has to convert the nvarchar &#8220;Australia&#8221; down to a varchar and do the comparison across every row in the table.</p><p>Thankfully there is a <a href="http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/d8577454-ebca-4697-80ef-73b7620e87a4">workaround</a> .</p><p>This problem has also been <a href="http://blogs.msdn.com/b/adonet/archive/2010/05/10/improvements-to-generated-sql-in-net-4-0.aspx">addressed</a> in EF 4.0 as well.</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2010/09/23/varchar-nvarchar-and-entity-framework/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Handling of Nulls in Entity Framework</title><link>http://quickduck.com/blog/2010/04/24/handling-of-nulls-in-entity-framework/</link> <comments>http://quickduck.com/blog/2010/04/24/handling-of-nulls-in-entity-framework/#comments</comments> <pubDate>Sat, 24 Apr 2010 05:44:21 +0000</pubDate> <dc:creator>Drew Freyling</dc:creator> <category><![CDATA[.Net]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Sql Server]]></category> <category><![CDATA[Data Access]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=270</guid> <description><![CDATA[I think most of you can agree that we are advocates of Entity Framework here. But sometimes things can get a little hairy (as with all ORM solutions). So I just thought I&#8217;d post a quick solution to a problem that had me tearing my hair out at work to solve the other day. Given the following [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2010/04/24/handling-of-nulls-in-entity-framework/"></g:plusone></div><p>I think most of you can agree that we are <a href="http://quickduck.com/blog/2009/05/18/abstracting-the-data-access-layer/">advocates of Entity Framework here</a>. But sometimes things can get a little hairy (as with all ORM solutions). So I just thought I&#8217;d post a quick solution to a problem that had me tearing my hair out at work to solve the other day.</p><p>Given the following two queries using Entity Framework one would assume the generated sql would the same?</p><pre class="brush: csharp; title: ; notranslate">
string country = null;
var query = context.Orders.Where(o =&gt; o.Customer.Address.Country == country);
var query2 = context.Orders.Where(o =&gt; o.Customer.Address.Country == null);
</pre><div>Wrong. Thanks to this <a href="https://connect.microsoft.com/data/feedback/details/545491/incorrect-handling-of-null-variables-in-where-clause" target="_blank">bug </a>and this <a href="http://msdn.microsoft.com/en-us/library/bb738687.aspx" target="_blank">Microsoft article</a>, I found out that not only will Entity Framwork will not honour what I have specified for ANSI NULLs, it will result in two inconsistent sql queries as the first query will do a &#8220;@country = null&#8221; comparison while the second query will do a &#8220;Country IS NULL&#8221; comparison.</div><div>Now, while I get that just because two objects are null it doesn&#8217;t mean they are equal, the workaround here can result in some ugly looking linq queries! Thank you ever so much Microsoft :)</div> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2010/04/24/handling-of-nulls-in-entity-framework/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>SqlDependency and DateTime values</title><link>http://quickduck.com/blog/2008/09/22/sqldependency-and-datetime-values/</link> <comments>http://quickduck.com/blog/2008/09/22/sqldependency-and-datetime-values/#comments</comments> <pubDate>Mon, 22 Sep 2008 14:53:04 +0000</pubDate> <dc:creator>Gerrod</dc:creator> <category><![CDATA[C#]]></category> <category><![CDATA[Sql Server]]></category><guid isPermaLink="false">http://quickduck.com/blog/2008/09/22/sqldependency-and-datetime-values/</guid> <description><![CDATA[I ran into a problem today where I was trying to set up a SqlDependency against a table, with what I thought was a plain vanilla select statement: private const string SqlCommandText = "Select ImportDate From dbo.Imports Where ImportDate = '{0:yyyyMMdd}'"; I was formatting this string with a date/time value at runtime, then passing that [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2008/09/22/sqldependency-and-datetime-values/"></g:plusone></div><p>I ran into a problem today where I was trying to set up a SqlDependency against a table, with what I thought was a plain vanilla select statement:</p><pre><code>
private const string SqlCommandText =
    "Select ImportDate From dbo.Imports Where ImportDate = '{0:yyyyMMdd}'";
</code></pre><p>I was formatting this string with a date/time value at runtime, then passing that into my SqlCommand object, then attempting to register the dependency. Well guess what &#8211; it didn&#8217;t work! The SqlNotificationEventArgs class kept telling me that my statement was invalid. Checking the <a href="http://msdn.microsoft.com/en-us/library/aewzkxxh.aspx">special considerations using query notifications</a>, I couldn&#8217;t see anything wrong with my query, so I was a bit lost.</p><p>Anyway, I decided to axe the &#8220;Where&#8221; condition from my query, and sure enough, it worked! So, by process of elimination, I figured it was something to do with converting a date from a character string that was throwing it. Not sure why; this works fine when run as T-Sql, or within a normal query&#8230;</p><p>To get around this problem, I used the &#8220;best practice&#8221; approach of using a parameter in the SqlCommand object:</p><pre><code>
private const string SqlCommandText =
    "Select ImportDate From dbo.Imports Where ImportDate = @ImportDate";

protected SqlCommand CreateSqlCommand() {
    var command = new SqlCommand(SqlCommandText);
    command.Parameters.Add(new SqlParameter("ImportDate", SqlDbType.DateTime) {
        Value = PositionDate
    });

    return command;
}
</code></pre><p>To my surprise, this worked a treat! I guess in the end, it wasn&#8217;t all that surprising, however I for some reason thought that using a parameter would surely not work; hence the reason I was pre-formatting the date/time in the first place!</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2008/09/22/sqldependency-and-datetime-values/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Running Sql Server scripts in .Net code</title><link>http://quickduck.com/blog/2008/02/20/running-sql-server-scripts-in-net-code/</link> <comments>http://quickduck.com/blog/2008/02/20/running-sql-server-scripts-in-net-code/#comments</comments> <pubDate>Wed, 20 Feb 2008 09:00:29 +0000</pubDate> <dc:creator>Ben</dc:creator> <category><![CDATA[.Net]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Development]]></category> <category><![CDATA[Sql Server]]></category><guid isPermaLink="false">http://quickduck.com/blog/2008/02/20/running-sql-server-scripts-in-net-code/</guid> <description><![CDATA[If you want to run sql server scripts through code, you can&#8217;t just run a standard ExecuteNonQuery() with a SqlCommand. There&#8217;s problems with ExecuteNonQuery() recognizing multiple sql statements. Don&#8217;t fear though, if you reference the Microsoft.SqlServer.Smo and Microsoft.SqlServer.ConnectionInfo assemblies you get access to some goodies that&#8217;ll help you on your way! using System.Configuration; using System.Data; [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2008/02/20/running-sql-server-scripts-in-net-code/"></g:plusone></div><p>If you want to run sql server scripts through code, you can&#8217;t just run a standard ExecuteNonQuery() with a SqlCommand. There&#8217;s problems with ExecuteNonQuery() recognizing multiple sql statements.</p><p>Don&#8217;t fear though, if you reference the Microsoft.SqlServer.Smo and Microsoft.SqlServer.ConnectionInfo assemblies you get access to some goodies that&#8217;ll help you on your way!</p><pre><code>
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBName"].ConnectionString);
Server server = new Server(new ServerConnection(connection));
server.ConnectionContext.ExecuteNonQuery(File.ReadAllText("SqlScript.sql"));

</code></pre>]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2008/02/20/running-sql-server-scripts-in-net-code/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Persisting objects into database using xml serialization</title><link>http://quickduck.com/blog/2008/02/18/persisting-objects-into-database-using-xml-serialization/</link> <comments>http://quickduck.com/blog/2008/02/18/persisting-objects-into-database-using-xml-serialization/#comments</comments> <pubDate>Mon, 18 Feb 2008 11:56:00 +0000</pubDate> <dc:creator>Ben</dc:creator> <category><![CDATA[.Net]]></category> <category><![CDATA[Development]]></category> <category><![CDATA[Sql Server]]></category> <category><![CDATA[Xml]]></category><guid isPermaLink="false">http://quickduck.com/blog/2008/02/18/55/</guid> <description><![CDATA[Recently I showed you how to pull sql query result sets into object instances using the XmlReader and deserialization. This article aims to show you the opposite process &#8211; persisting an object instance into a database table using serialization and Sql Server xml parsing. The same Channel database table and entity class will be used [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2008/02/18/persisting-objects-into-database-using-xml-serialization/"></g:plusone></div><p>Recently I <a href="http://quickduck.com/blog/2008/02/15/using-xmlreader-to-go-from-sql-result-set-to-a-list-of-objects/">showed</a> you how to pull sql query result sets into object instances using the XmlReader and deserialization. This article aims to show you the opposite process &#8211; persisting an object instance into a database table using serialization and Sql Server xml parsing.</p><p>The same Channel database table and entity class will be used for all examples.</p><p><img src='http://quickduck.com/blog/wp-content/uploads/2008/02/channeltable.JPG' alt='Channel Table Schema' /></p><pre class="brush: csharp; title: ; notranslate">/// Represents a media channel (e.g. web, mobile, iphone, etc.)
public class Channel
{
   public Channel()
   {
   }

   public Channel(string type, string description)
   {
       Type = type;
       Description = description;
   }

    /// Get/Set the channel identifier
    public int Id { get; set; }

    /// Get/Set the channel type (e.g. web, mobile, iphone, etc.)
    public string Type { get; set; }

    /// Get/Set the description of the channel.
    public string Description { get; set; }
 }</pre><h2>The Stored Procedure</h2><p>The sproc takes in an sql server xml datatype parameter. This is provided via a normal string representation of the xml. Within the SPROC you prepare the document for querying, pull out the values you require and perform the insert.</p><p>To understand the following SPROC, you need to have have a basic understanding of:</p><p><strong>a)</strong> how your object instance xml serialization format looks</p><pre><code>
&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Channel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  &lt;Id>0&lt;/Id&gt;
  &lt;Type>web&lt;/Type&gt;
  &lt;Description>800x600 or larger browsers&lt;/Description&gt;
&lt;/Channel&gt;'
</code></pre><p>and</p><p><strong>b)</strong> an understanding of xpath and xquery for pulling the values out from the xml.</p><p>Check out the &#8211; <a href="http://quickduck.com/blog/sqlxml/">Resources &#8211; Sql Xml </a>- for some links that might help you out.</p><pre><code>
CREATE PROCEDURE [usp_PersistChannel]
	@xmldoc XML
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE
            @iDoc int,
            @type varchar(50),
            @description varchar(255)

    EXEC sp_xml_preparedocument
           @iDoc OUTPUT,
           @xmldoc,
            '<Channel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />'

    SELECT
            @Type = [Type],
            @Description = [Description]
    FROM
            OPENXML (@iDoc, '/Channel',3)
	WITH (  [Type] varchar(50) './Type',
	Description] varchar(255) './Description' )

    EXEC sp_xml_removedocument @idoc

    INSERT INTO Channel VALUES (@Type, @Description)                

    SELECT @@IDENTITY
END
</code></pre><h2>Data Access Code</h2><p>The following is a convenience method to help aid the serialization process of an object instance.</p><pre><code>
        /// Serialize an instance of an object to a string.
        public string Serialize(object instance)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            XmlSerializer serializer = new XmlSerializer(instance.GetType(), null, new Type[0], null, null);
            serializer.Serialize(sw, instance);
            return sb.ToString();
        }
</code></pre><h2>Usage Examples:</h2><pre><code>

        /// Persist a Channel.
        public void Persist(Channel channel)
        {
            channel.Id = Int32.Parse(
                                Database.ExecuteScalar(
                                   Database.GetStoredProcCommand("usp_PersistChannel", Serialize(channel))
                                ).ToString()
                             );
        }
</code></pre>]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2008/02/18/persisting-objects-into-database-using-xml-serialization/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Using XmlReader and object Deserialization</title><link>http://quickduck.com/blog/2008/02/15/using-xmlreader-to-go-from-sql-result-set-to-a-list-of-objects/</link> <comments>http://quickduck.com/blog/2008/02/15/using-xmlreader-to-go-from-sql-result-set-to-a-list-of-objects/#comments</comments> <pubDate>Fri, 15 Feb 2008 10:31:27 +0000</pubDate> <dc:creator>Ben</dc:creator> <category><![CDATA[.Net]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Sql Server]]></category> <category><![CDATA[Data Access]]></category> <category><![CDATA[XmlReader]]></category><guid isPermaLink="false">http://quickduck.com/blog/2008/02/15/using-xmlreader-to-go-from-sql-result-set-to-a-list-of-objects/</guid> <description><![CDATA[These days there seems to be an infinte number of ways to take data returned from the database and map them into your object model. This article aims to simple show you how to generically map the sql select result set into a list of object instances in your code. First things first, the code [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2008/02/15/using-xmlreader-to-go-from-sql-result-set-to-a-list-of-objects/"></g:plusone></div><p>These days there seems to be an infinte number of ways to take data returned from the database and map them into your object model.</p><p>This article aims to simple show you how to generically map the sql select result set into a list of object instances in your code.</p><p>First things first, the code illustrated here requires Sql Server 2005, and .Net 2.0+ framework.</p><h2>Sql Server 2005 Queries</h2><p>It doesn&#8217;t matter whether you write you queries in code or by using Sql Server SProcs, simple by adding &#8211; &#8216;FOR XML Path(&#8216;ElementName&#8217;) &#8211; the following to the end of you Select statement, Sql Server will return your result sets in Xml.</p><pre><code>
Syntax: 

SELECT * FROM [TableName] WITH (nolock) FOR XML PATH('TableName')

</code></pre><pre><code>
Example:

SELECT * FROM [Channel] WITH (nolock) FOR XML PATH('Channel')

Results:

&lt;Channel&gt;
  &lt;Id&gt;1&lt;/Id&gt;
  &lt;Type&gt;web&lt;/Type&gt;
  &lt;Description&gt;standard internet&lt;/Description&gt;
&lt;/Channel&gt;
&lt;Channel&gt;
  &lt;Id>3&lt;/Id&gt;
  &lt;Type>mobile&lt;/Type&gt;
  &lt;Description>mobile&lt;/Description&gt;
&lt;/Channel&gt;

</code></pre><p>The parameter passed into the Path() statement determines the top level element name &#8211; allowing you to shape the xml.</p><h2>The Entity POCOs</h2><p>Using the .Net built in xml to class deserialization process, the returned xml will map the top level element to a class name and each sub-element to a public property/member on the object class.</p><p>Let&#8217;s create the Plain Old C# Object to enable deserialization.</p><pre><code>
/// Represents a media channel (e.g. web, mobile, iphone, etc.)
public class Channel    {
  private int _id;
  private string _type, _description;

  public Channel(){}

  public Channel(string type, string description)  {
    _type = type;
    _description = description;
  }

  /// Get/Set the channel identifier
  public int Id {
    get { return _id; }
    set { _id = value; }
  }

  /// Get/Set the channel type (e.g. web, mobile, iphone, etc.)
  public string Type {
    get { return _type; }
    set { _type = value; }
  }

  /// Get/Set the description of the channel.
  public string Description {
    get { return _description; }
    set { _description = value; }
  }
}
</code></pre><p><strong>NOTE:</strong> If there are differences in your database schema naming conventions to how you name things in your classes you will need to shape the xml somewhere to make the deserialization process work.</p><p>You have two options: you can decorate your class with appropriate Xml Serialization Attributes <strong>OR</strong> you can change your Sql Query.</p><p>Example: the Channel table has a column name <em>desc</em> but you need to map to the public property name <em>Description</em>.</p><p><strong>Scenario 1:</strong> Shape the xml using the [XmlAttribute]</p><pre><code>
  [XmlAttribute("desc")]
  public string Description {
    get { return _description; }
    set { _description = value; }
  }
</code></pre><p>OR</p><p><strong>Scenario 2:</strong> Shape the xml in your Sql Query</p><pre><code>
SELECT [Id], [Type], [Desc] as Description
FROM [Channel]
WITH (nolock)
FOR XML PATH('Channel')
</code></pre><h2>Data Access Code</h2><p>Ok. You know how to get the data back from the DB in Xml. Now it&#8217;s time to read the results into a list of the entity POCOs.</p><pre><code>
  private static readonly IDictionary<Type, XmlSerializer> xmlSerializers = new Dictionary<Type, XmlSerializer>();

  /// Generic helper method for reading sql server table rows into entities.
  internal IList<T> GetEntities<T>(DbCommand dbCommand)  {
    IList<T> entities = new List<T>();
    using (XmlReader reader = ((SqlDatabase) Database).ExecuteXmlReader(dbCommand))  {
      while (!reader.EOF) {
        if (reader.IsStartElement()) {
          entities.Add(Deserialize<T>(reader.ReadOuterXml()));
        }
      }
    }
    return entities;
  }

  /// Deserialize an xml fragment into the specified Type.
  public T Deserialize<T>(string xml)  {
    using (StringReader sr = new StringReader(xml)) {
      if (!xmlSerializers.ContainsKey(typeof (T))){
        xmlSerializers.Add(typeof (T), new XmlSerializer(typeof (T), null, new Type[0], null, null));
      }
      XmlSerializer serializer = xmlSerializers[typeof (T)];
      return (T) serializer.Deserialize(sr);
    }
  }
</code></pre><p><strong>NOTE:</strong> I cache an XmlSerialzer instance for each Type because the .Net framework generates a class dynamically at runtime when the new XmlSerializer() constructor is called. If you have thousands of results coming back from the DB this is timely and memory consuming.</p><h2>Usage Examples:</h2><pre></code>
/// Get a specific Channel.
public Channel GetChannel(string name) {
  IList<Channel> list = GetEntities<Channel>(Database.GetStoredProcCommand("usp_GetChannels", 0, name));
  return (list != null &#038;&#038; list.Count == 1) ? list[0] : null;
}

/// Get a list of all Channels.
public IList<Channel> GetChannels() {
  return GetEntities<Channel>(Database.GetStoredProcCommand("usp_GetChannels", 0, null));
}
</code></pre><p>That&#8217;s it!</p><p><strong>Update: 18-Feb-08</strong> I&#8217;ve written a followup article that shows how to do the reverse process &#8211; <a href="http://quickduck.com/blog/2008/02/18/persisting-objects-into-database-using-xml-serialization/">Persisting objects into database using xml serialization</a></p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2008/02/15/using-xmlreader-to-go-from-sql-result-set-to-a-list-of-objects/feed/</wfw:commentRss> <slash:comments>9</slash:comments> </item> <item><title>Sql timeout &#8211; a trap for young players!</title><link>http://quickduck.com/blog/2006/12/22/sql-timeout-a-trap-for-young-players/</link> <comments>http://quickduck.com/blog/2006/12/22/sql-timeout-a-trap-for-young-players/#comments</comments> <pubDate>Fri, 22 Dec 2006 18:57:56 +0000</pubDate> <dc:creator>Gerrod</dc:creator> <category><![CDATA[Asp.Net]]></category> <category><![CDATA[Sql Server]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=17</guid> <description><![CDATA[I was talking to one of the guys at work about Sql timeouts. He had a long running operation &#8211; about 40 seconds &#8211; so to compensate for this, he set the timeout on his connection string to one minute: &#60;connectionStrings&#62; &#60;add name="cs" connectionString="Data Source=localhost;Initial Catalog=MyDB;Connection Timeout=60;" &#60;/connectionStrings&#62; Sure looks OK, but as it turns [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2006/12/22/sql-timeout-a-trap-for-young-players/"></g:plusone></div><p>I was talking to one of the guys at work about Sql timeouts. He had a long running operation &#8211; about 40 seconds &#8211; so to compensate for this, he set the timeout on his connection string to one minute:</p><pre><code>
&lt;connectionStrings&gt;
  &lt;add name="cs"
    connectionString="Data Source=localhost;Initial Catalog=MyDB;Connection Timeout=60;"
&lt;/connectionStrings&gt;
</code></pre><p>Sure looks OK, but as it turns out, this wasn&#8217;t working for him. The reason is actually quite straightforward &#8211; the <b>Connection Timeout</b> property is used to specify how long the application will wait to <i>establish</i> a connection to the server before giving up and throwing an exception. In most cases (where connections are properly managed), the connection will be returned almost instantaneously, hence changing this value is usually not required.</p><p>Instead, the timeout that he needed to change was the <b>CommandTimeout</b> on the SqlCommand object which was being passed to the database.</p><pre><code>
  SqlCommand command = new SqlCommand();
  command.CommandTimeout = 60;
</pre><p></code></p><p>As the MSDN doco states, this property "Gets or sets the wait time before terminating the attempt to execute a command and generating an error". And sure enough, once he changed this value to 60, everything was dandy.</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2006/12/22/sql-timeout-a-trap-for-young-players/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>SQL Compare</title><link>http://quickduck.com/blog/2006/12/01/sql-compare/</link> <comments>http://quickduck.com/blog/2006/12/01/sql-compare/#comments</comments> <pubDate>Fri, 01 Dec 2006 17:27:56 +0000</pubDate> <dc:creator>Gerrod</dc:creator> <category><![CDATA[Sql Server]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=8</guid> <description><![CDATA[Recently I made the unfortunate mistake of developing against an SQL Server 2005 database server, which I mistakenly thought was an SQL Server 2000 server. I know what you&#8217;re thinking, &#8220;how could you get that wrong?!&#8221; &#8211; but the reason was that the server was previously running 2000, and I had forgotten that it was [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2006/12/01/sql-compare/"></g:plusone></div><p>Recently I made the unfortunate mistake of developing against an SQL Server 2005 database server, which I mistakenly thought was an SQL Server 2000 server. I know what you&#8217;re thinking, &#8220;how could you get <i>that</i> wrong?!&#8221; &#8211; but the reason was that the server was <i>previously</i> running 2000, and I had forgotten that it was upgraded.</p><p>Anyway, this wasn&#8217;t really a problem (since I had compatibility level set to 8) &#8211; until it came to deploying the updated database. Turns out you can&#8217;t export a 2005 backup and restore it onto 2000 &#8211; no real surprises there! So my next option was to generate scripts to recreate the database on a SQL Server 2000 server, but guess what &#8211; the Generate Scripts tool in 2005 does NOT generate scripts compatible with 2000. Now that <i>was</i> a surprise, given that one of the options actually allows you to specify that the scripts are for Sql Server 2000!</p><p>After searching around the net for a solution, I concluded that my best option was to restore an old database backup, and then manually go through and make the changes. Clearly not a <i>good</i> option, since it was very likely that I&#8217;d be missing things left right and centre, but what choice did I have?</p><p>Lucky for me, a colleague happened to pay me a visit just as I was about to start, and told me that he had had my exact same problem only a few weeks ago. Better still, he had a tool which was effectively a diff/merge tool which worked across database versions. Sweet!</p><p>So I checked it out &#8211; <a href="http://www.red-gate.com/products/SQL_Compare/index.htm" target="_blank">RedGate&#8217;s SQL Compare</a> &#8211; and found it an absolute delight to use. It was able to update about 95% of the changes without manual intervention. The other 5% was also a simple change &#8211; since SQL Compare had generated a script to do the upgrades, all I had to do was make a few minor tweaks.</p><p>My only complaint with SQL Compare is that you can&#8217;t tell it <i>not</i> to synchronize/compare extended properties of objects. (Extended properties define stuff like layouts of diagrams, etc). If I could have turned this off, it would have been able to do the entire upgrade without any intervention from me. Still, overall, this is an awesome piece of software, and it gets my highest recommendation.</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2006/12/01/sql-compare/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Generating Sql Server DB object scripts</title><link>http://quickduck.com/blog/2006/11/24/generating-sql-server-db-object-scripts/</link> <comments>http://quickduck.com/blog/2006/11/24/generating-sql-server-db-object-scripts/#comments</comments> <pubDate>Fri, 24 Nov 2006 15:30:21 +0000</pubDate> <dc:creator>Ben</dc:creator> <category><![CDATA[Development]]></category> <category><![CDATA[Sql Server]]></category><guid isPermaLink="false">http://quickduck.com/blog/?p=7</guid> <description><![CDATA[Have you ever wanted to script all the db objects in your database and customize how you format the scripts? So have I! Ideally, I wanted to script all the db objects (eg. procs, udfs, grants, defaults, permissions, tables, etc) and have each object output into a separate file and formatted a particular way. So [...]]]></description> <content:encoded><![CDATA[<div class="google_plus_one"><g:plusone size="standard" count="false" url="http://quickduck.com/blog/2006/11/24/generating-sql-server-db-object-scripts/"></g:plusone></div><p>Have you ever wanted to script all the db objects in your database and customize how you format the scripts?</p><p>So have I!</p><p>Ideally, I wanted to script all the db objects (eg. procs, udfs, grants, defaults, permissions, tables, etc) and have each object output into a separate file and formatted a particular way.</p><p>So I&#8217;ve <a href="http://quickduck.com/blog/wp-content/uploads/2006/11/CreateSqlScripts.sql">created a couple of sprocs</a> that allow you to do this.</p><blockquote><p> Usage:<br /> EXEC dbo.CreateSqlScripts<br /> &#8216;&lt;directory&gt;&#8217;, &#8216;&lt;sqlServerInstance&gt;&#8217;, &#8216;&lt;dbname&gt;&#8217;, &#8216;&lt;object type or null&gt;&#8217;, &#8216;&lt;formattingoptions&gt;&#8217;</p><p> Example:<br /> EXEC dbo.CreateSqlScripts<br /> &#8216;c:\temp\sql\&#8217;, &#8216;localhost\SQLLOCALMACHINE&#8217;, &#8216;MyDB&#8217;, NULL, 73879  &#8212; all db objects</p><p> Example:<br /> EXEC dbo.CreateSqlScripts<br /> &#8216;c:\temp\sql\&#8217;, &#8216;localhost\SQLLOCALMACHINE&#8217;, &#8216;MyDB&#8217;, &#8216;P&#8217;, 73879      &#8212; stored procedures only</p></blockquote><p>A bonus feature of having your db scripted out is that you can use a 3rd party program like <a href="http://www.innovartis.co.uk/" target="_blank">DBGhost</a> to generate a new db from the scripts directory.</p><p>This is really handy if you want to have your db source controlled.</p> ]]></content:encoded> <wfw:commentRss>http://quickduck.com/blog/2006/11/24/generating-sql-server-db-object-scripts/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced

Served from: quickduck.com @ 2012-02-05 17:02:28 -->
