<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>using ...</title>
	<atom:link href="http://esersahin.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://esersahin.wordpress.com</link>
	<description>Pure C#</description>
	<lastBuildDate>Sun, 22 Nov 2009 18:23:32 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>tr</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='esersahin.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/929ac32e225b9b8a92739f08a8b4f9e0?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>using ...</title>
		<link>http://esersahin.wordpress.com</link>
	</image>
			<item>
		<title>Enterprise Library 5.0 &#8211; Dev Guide</title>
		<link>http://esersahin.wordpress.com/2009/11/22/enterprise-library-5-0-dev-guide/</link>
		<comments>http://esersahin.wordpress.com/2009/11/22/enterprise-library-5-0-dev-guide/#comments</comments>
		<pubDate>Sun, 22 Nov 2009 18:23:32 +0000</pubDate>
		<dc:creator>esersahin</dc:creator>
				<category><![CDATA[Enterprise Library]]></category>

		<guid isPermaLink="false">http://esersahin.wordpress.com/?p=1438</guid>
		<description><![CDATA[http://entlib.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=35832
Release Notes

Zen and the Art of Managing Crosscutting Concerns in Enterprise Software Development
A Guide to Developing with Enterprise Library 5.0 (C# Edition) &#8211; PREVIEW

Posted in Enterprise Library       <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1438&subd=esersahin&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>http://entlib.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=35832</p>
<h3>Release Notes</h3>
<div><img src="http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=entlib&amp;DownloadId=92680" alt="" /></p>
<h1>Zen and the Art of Managing Crosscutting Concerns in Enterprise Software Development</h1>
<h2>A Guide to Developing with Enterprise Library 5.0 (C# Edition) &#8211; PREVIEW</h2>
</div>
Posted in Enterprise Library  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/esersahin.wordpress.com/1438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/esersahin.wordpress.com/1438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/esersahin.wordpress.com/1438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/esersahin.wordpress.com/1438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/esersahin.wordpress.com/1438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/esersahin.wordpress.com/1438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/esersahin.wordpress.com/1438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/esersahin.wordpress.com/1438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/esersahin.wordpress.com/1438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/esersahin.wordpress.com/1438/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1438&subd=esersahin&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://esersahin.wordpress.com/2009/11/22/enterprise-library-5-0-dev-guide/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8e21407efc4fee973e107f07af76dc73?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">DarkStar</media:title>
		</media:content>

		<media:content url="http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=entlib&#38;DownloadId=92680" medium="image" />
	</item>
		<item>
		<title>Visual Studio 2008 and .NET Framework 3.5 Training Kit</title>
		<link>http://esersahin.wordpress.com/2009/11/21/visual-studio-2008-and-net-framework-3-5-training-kit/</link>
		<comments>http://esersahin.wordpress.com/2009/11/21/visual-studio-2008-and-net-framework-3-5-training-kit/#comments</comments>
		<pubDate>Sat, 21 Nov 2009 07:40:55 +0000</pubDate>
		<dc:creator>esersahin</dc:creator>
				<category><![CDATA[.Net 3.5]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>

		<guid isPermaLink="false">http://esersahin.wordpress.com/2009/11/21/visual-studio-2008-and-net-framework-3-5-training-kit/</guid>
		<description><![CDATA[http://www.microsoft.com/downloads/details.aspx?FamilyID=8BDAA836-0BBA-4393-94DB-6C3C4A0C98A1&#38;displaylang=en
The Visual Studio 2008 and .NET Framework 3.5 Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio 2008 features and a variety of framework technologies including: LINQ, C# 3.0, Visual Basic 9, WCF, WF, WPF, ASP.NET AJAX, VSTO, CardSpace, SilverLight, Mobile and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1436&subd=esersahin&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>http://www.microsoft.com/downloads/details.aspx?FamilyID=8BDAA836-0BBA-4393-94DB-6C3C4A0C98A1&amp;displaylang=en</p>
<p>The Visual Studio 2008 and .NET Framework 3.5 Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio 2008 features and a variety of framework technologies including: LINQ, C# 3.0, Visual Basic 9, WCF, WF, WPF, ASP.NET AJAX, VSTO, CardSpace, SilverLight, Mobile and Application Lifecycle Management.</p>
Posted in .Net 3.5, Visual Studio 2008  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/esersahin.wordpress.com/1436/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/esersahin.wordpress.com/1436/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/esersahin.wordpress.com/1436/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/esersahin.wordpress.com/1436/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/esersahin.wordpress.com/1436/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/esersahin.wordpress.com/1436/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/esersahin.wordpress.com/1436/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/esersahin.wordpress.com/1436/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/esersahin.wordpress.com/1436/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/esersahin.wordpress.com/1436/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1436&subd=esersahin&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://esersahin.wordpress.com/2009/11/21/visual-studio-2008-and-net-framework-3-5-training-kit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8e21407efc4fee973e107f07af76dc73?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">DarkStar</media:title>
		</media:content>
	</item>
		<item>
		<title>Visual Studio 2010 and .NET Framework 4 Training Course</title>
		<link>http://esersahin.wordpress.com/2009/11/21/visual-studio-2010-and-net-framework-4-training-course/</link>
		<comments>http://esersahin.wordpress.com/2009/11/21/visual-studio-2010-and-net-framework-4-training-course/#comments</comments>
		<pubDate>Sat, 21 Nov 2009 07:34:40 +0000</pubDate>
		<dc:creator>esersahin</dc:creator>
				<category><![CDATA[.Net 4.0]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>

		<guid isPermaLink="false">http://esersahin.wordpress.com/?p=1433</guid>
		<description><![CDATA[http://channel9.msdn.com/learn/courses/vs2010/
The Visual  Studio 2010 and .NET Framework 4 Training Course includes videos and  hands-on-labs designed to help you learn how to utilize the Visual Studio 2010  features and a variety of framework technologies including: C# 4.0, Visual Basic  10, F#, Parallel Computing Platform, WCF, WF, WPF, ASP.NET AJAX 4.0, ASP.NET MVC [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1433&subd=esersahin&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>http://channel9.msdn.com/learn/courses/vs2010/</p>
<p>The Visual  Studio 2010 and .NET Framework 4 Training Course includes videos and  hands-on-labs designed to help you learn how to utilize the Visual Studio 2010  features and a variety of framework technologies including: C# 4.0, Visual Basic  10, F#, Parallel Computing Platform, WCF, WF, WPF, ASP.NET AJAX 4.0, ASP.NET MVC  Dynamic Data.</p>
Posted in .Net 4.0, Visual Studio 2010  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/esersahin.wordpress.com/1433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/esersahin.wordpress.com/1433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/esersahin.wordpress.com/1433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/esersahin.wordpress.com/1433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/esersahin.wordpress.com/1433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/esersahin.wordpress.com/1433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/esersahin.wordpress.com/1433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/esersahin.wordpress.com/1433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/esersahin.wordpress.com/1433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/esersahin.wordpress.com/1433/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1433&subd=esersahin&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://esersahin.wordpress.com/2009/11/21/visual-studio-2010-and-net-framework-4-training-course/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8e21407efc4fee973e107f07af76dc73?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">DarkStar</media:title>
		</media:content>
	</item>
		<item>
		<title>Visual Studio 2010 and .NET Framework 4 Training Kit &#8211; October Preview</title>
		<link>http://esersahin.wordpress.com/2009/11/21/visual-studio-2010-and-net-framework-4-training-kit-october-preview/</link>
		<comments>http://esersahin.wordpress.com/2009/11/21/visual-studio-2010-and-net-framework-4-training-kit-october-preview/#comments</comments>
		<pubDate>Sat, 21 Nov 2009 07:31:44 +0000</pubDate>
		<dc:creator>esersahin</dc:creator>
				<category><![CDATA[.Net 4.0]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>

		<guid isPermaLink="false">http://esersahin.wordpress.com/2009/11/21/visual-studio-2010-and-net-framework-4-training-kit-october-preview/</guid>
		<description><![CDATA[http://www.microsoft.com/downloads/details.aspx?familyid=752CB725-969B-4732-A383-ED5740F02E93&#38;displaylang=en
The Visual Studio 2010 and  .NET Framework 4 Training Kit includes presentations, hands-on labs, and demos.  This content is designed to help you learn how to utilize the Visual Studio 2010  features and a variety of framework technologies including:

C# 4.0
Visual Basic 10
F#
Parallel Extensions
Windows Communication Foundation
Windows Workflow
Windows Presentation Foundation
ASP.NET 4
Windows 7
Entity Framework
ADO.NET Data [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1432&subd=esersahin&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>http://www.microsoft.com/downloads/details.aspx?familyid=752CB725-969B-4732-A383-ED5740F02E93&amp;displaylang=en</p>
<div><a name="Description"></a>The Visual Studio 2010 and  .NET Framework 4 Training Kit includes presentations, hands-on labs, and demos.  This content is designed to help you learn how to utilize the Visual Studio 2010  features and a variety of framework technologies including:</p>
<ul>
<li>C# 4.0</li>
<li>Visual Basic 10</li>
<li>F#</li>
<li>Parallel Extensions</li>
<li>Windows Communication Foundation</li>
<li>Windows Workflow</li>
<li>Windows Presentation Foundation</li>
<li>ASP.NET 4</li>
<li>Windows 7</li>
<li>Entity Framework</li>
<li>ADO.NET Data Services</li>
<li>Managed Extensibility Framework</li>
<li>Visual Studio Team System</li>
</ul>
<p>This version of the Training Kit works  with Visual Studio 2010 Beta 2 and .NET Framework 4 Beta 2.</p></div>
Posted in .Net 4.0, Visual Studio 2010  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/esersahin.wordpress.com/1432/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/esersahin.wordpress.com/1432/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/esersahin.wordpress.com/1432/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/esersahin.wordpress.com/1432/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/esersahin.wordpress.com/1432/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/esersahin.wordpress.com/1432/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/esersahin.wordpress.com/1432/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/esersahin.wordpress.com/1432/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/esersahin.wordpress.com/1432/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/esersahin.wordpress.com/1432/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1432&subd=esersahin&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://esersahin.wordpress.com/2009/11/21/visual-studio-2010-and-net-framework-4-training-kit-october-preview/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8e21407efc4fee973e107f07af76dc73?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">DarkStar</media:title>
		</media:content>
	</item>
		<item>
		<title>Dynamic/Conditional Order By Clause in SQL Server/T-SQL</title>
		<link>http://esersahin.wordpress.com/2009/11/11/dynamicconditional-order-by-clause-in-sql-servert-sql/</link>
		<comments>http://esersahin.wordpress.com/2009/11/11/dynamicconditional-order-by-clause-in-sql-servert-sql/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 16:21:52 +0000</pubDate>
		<dc:creator>esersahin</dc:creator>
				<category><![CDATA[Case When]]></category>
		<category><![CDATA[ORDER BY]]></category>

		<guid isPermaLink="false">http://esersahin.wordpress.com/?p=1429</guid>
		<description><![CDATA[http://www.dominicpettifer.co.uk/Blog/21/dynamic-conditional-order-by-clause-in-sql-server-t-sql
Technical Article &#8211; This article shows you how to achieve a conditional Order By clause in your SQL Server Stored Procedures, without having to resort to inline SQL in your applications, or Dynamic SQL (yuck!) in your Stored Procedures.
Inline SQL or Stored Procedures
You&#8217;ve probably come across times when you needed to sort a recordset dynamically [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1429&subd=esersahin&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>http://www.dominicpettifer.co.uk/Blog/21/dynamic-conditional-order-by-clause-in-sql-server-t-sql</p>
<p><strong>Technical Article</strong> &#8211; This article shows you how to achieve a conditional Order By clause in your SQL Server Stored Procedures, without having to resort to inline SQL in your applications, or Dynamic SQL (yuck!) in your Stored Procedures.</p>
<h2>Inline SQL or Stored Procedures</h2>
<p>You&#8217;ve probably come across times when you needed to sort a recordset dynamically in a Stored Procedure based on an input parameter. For instance, if you&#8217;re displaying records on a webpage with sortable columns, like on most ecommerce sites. You could use an inline SQL statement dynamically built in your ASP/PHP server-side code with string concatenation eg:</p>
<p><code>string sql = "SELECT * FROM Products ORDER BY ";</p>
<p>if(Request.QueryString["orderBy"] == "NameAsc")<br />
{<br />
sql += "Name ASC";<br />
}<br />
else if(Request.QueryString["orderBy"] == "NameDesc")<br />
{<br />
sql += "Name DESC";<br />
}<br />
else if(......etc etc</code></p>
<p>However, you&#8217;re probably using a Stored Procedure for reasons such as performance (execution plan is cached in a Sproc), maintainability (string concatenation can get messy with complex queries), prevent security vulnerabilities (such as <a href="http://en.wikipedia.org/wiki/SQL_injection">SQL Injection</a>), and maybe you want to achieve efficient database tier paging using SQL Server 2005&#8217;s <a href="http://www.davidhayden.com/blog/dave/archive/2005/12/30/2652.aspx">ROW_NUMBER()</a> function.</p>
<h2>Introducing the CASE Function</h2>
<p>The trick is to use the CASE function, but there are quirks with this that can trip you up. First of all you declare a Stored Procedure with an Order By input parameter and apply the CASE to the Order By clause like this:</p>
<p><code>CREATE PROCEDURE GetProducts<br />
(<br />
@OrderBy      VARCHAR(50),<br />
@Input2       VARCHAR(30)<br />
)<br />
AS<br />
BEGIN<br />
SET NOCOUNT ON</p>
<p>SELECT Id, ProductName, Description, Price, Quantity<br />
FROM Products<br />
WHERE ProductName LIKE @Input2<br />
ORDER BY<br />
CASE<br />
WHEN @OrderBy = 'ProductNameAsc' THEN ProductName<br />
END ASC,<br />
CASE<br />
WHEN @OrderBy = 'ProductNameDesc' THEN ProductName<br />
END DESC</p>
<p>END</code></p>
<p>Ascending and Descending actions need to be grouped into separate CASE statements, separated with a comma. In your server-side code/script make sure to append &#8216;Asc&#8217; or &#8216;Desc&#8217; onto the order by string, or you could have two Stored procedure input parameters for column name and order by direction if you want.</p>
<h2>Multiple Columns with Different DataTypes</h2>
<p>You&#8217;ll hit problems when you try to include multiple columns with different data types (VARCHAR, INT etc.). Eg:</p>
<p><code>ORDER BY<br />
CASE<br />
WHEN @OrderBy = 'ProductNameAsc' THEN ProductName<br />
WHEN @OrderBy = 'QuantityAsc' THEN Quantity<br />
END ASC</code></p>
<p>&#8230;will throw an error because ProductName is a VARCHAR and Quantity is an INT&#8230;</p>
<p><strong>Conversion failed when converting the nvarchar value &#8216;Value&#8217; to data type int.<br />
Warning: Null value is eliminated by an aggregate or other SET operation.</strong></p>
<p>I&#8217;ve seen people wrap the column around a convert function eg.</p>
<p><code>WHEN @OrderBy = 'QuantityAsc' THEN CONVERT(VARCHAR(32), Quantity)</code></p>
<p><strong>DON’T</strong> do this as the order by will be different as a string versus it&#8217;s original data type (eg. 30 will come before 4 as the first character 3 is earlier in the alphebet then 4). This is especially true with DATETIME types as the CONVERT function could convert to into any number of date time formats (2009/01/15, 01/15/2009 etc.)</p>
<p>Instead you have to separate each datatype into separate groups of case statements like this:</p>
<p><code>SELECT Id, ProductName, Description, Price, Quantity<br />
FROM Products<br />
WHERE ProductName LIKE @Input2<br />
ORDER BY<br />
CASE –- VARCHAR types ascending<br />
WHEN @OrderBy = 'ProductNameAsc' THEN ProductName<br />
END ASC,<br />
CASE –- VARCHAR types descending<br />
WHEN @OrderBy = 'ProductNameDesc' THEN ProductName<br />
END DESC,<br />
CASE -- INT types ascending<br />
WHEN @OrderBy = 'QuantityAsc' THEN Quantity<br />
END ASC,<br />
CASE -- INT types descending<br />
WHEN @OrderBy = 'QuantityDesc' THEN Quantity<br />
END DESC,<br />
CASE -- MONEY types ascending<br />
WHEN @OrderBy = 'PriceAsc' THEN Price<br />
END ASC,<br />
CASE -- MONEY types descending<br />
WHEN @OrderBy = 'PriceDesc' THEN Price<br />
END DESC,<br />
CASE -- Default order by<br />
WHEN 1 = 1 THEN ProductName<br />
END ASC</code></p>
<p>Remember to provide a default Order By for when none of the CASE statements match.</p>
<h2>Paging With ROW_NUMBER()</h2>
<p>You can also use this technique with database tier paging using the ROW_NUMBER() function in SQL Server 2005/2008:</p>
<p><code>SELECT<br />
Id,<br />
ProductName,<br />
Deacription,<br />
Quantity<br />
FROM<br />
(<br />
SELECT ROW_NUMBER() OVER(<br />
ORDER BY<br />
CASE<br />
WHEN @OrderBy = 'ProductNameAsc' THEN ProductName<br />
END ASC,<br />
CASE<br />
WHEN @OrderBy = 'ProductNameDesc' THEN ProductName<br />
END DESC,<br />
CASE<br />
WHEN 1 = 1 THEN ProductName<br />
END ASC,<br />
//-- Snip --//<br />
) AS RowNumber,<br />
Id,<br />
ProductName,<br />
Description,<br />
Price,<br />
Quantity<br />
FROM Products<br />
WHERE ProductName LIKE @Input2<br />
) i<br />
WHERE RowNmber BETWEEN @FirstRecord AND @LastRecord<br />
ORDER BY RowNumber ASC</code></p>
Posted in Case When, ORDER BY  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/esersahin.wordpress.com/1429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/esersahin.wordpress.com/1429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/esersahin.wordpress.com/1429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/esersahin.wordpress.com/1429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/esersahin.wordpress.com/1429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/esersahin.wordpress.com/1429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/esersahin.wordpress.com/1429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/esersahin.wordpress.com/1429/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/esersahin.wordpress.com/1429/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/esersahin.wordpress.com/1429/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1429&subd=esersahin&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://esersahin.wordpress.com/2009/11/11/dynamicconditional-order-by-clause-in-sql-servert-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8e21407efc4fee973e107f07af76dc73?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">DarkStar</media:title>
		</media:content>
	</item>
		<item>
		<title>Case in Where Clause</title>
		<link>http://esersahin.wordpress.com/2009/11/11/case-in-where-clause/</link>
		<comments>http://esersahin.wordpress.com/2009/11/11/case-in-where-clause/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 12:22:08 +0000</pubDate>
		<dc:creator>esersahin</dc:creator>
				<category><![CDATA[Case When]]></category>
		<category><![CDATA[Where Clause]]></category>

		<guid isPermaLink="false">http://esersahin.wordpress.com/?p=1427</guid>
		<description><![CDATA[http://p2p.wrox.com/sql-server-2000/832-case-where-clause.html
Hi everybody
Can I use case statement in WHERE clause.
For example
DECLARE @VAR1 nvarchar(50)
DECLARE @VAR2 nvarchar(50)
SELECT * FROM ORDERS
WHERE CASE @VAR1
          WHEN &#8216;Customers&#8217; THEN CustomerID = @VAR2
          WHEN &#8216;Employee&#8217; THEN EmployeeID = @VAR2
          END
This is not working OK.
Can someone explain me the right way?
Thanks.
Best regards
Alex
&#160;
In your situation, where you wish to select on two entirely different columns depending on a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1427&subd=esersahin&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://p2p.wrox.com/sql-server-2000/832-case-where-clause.html">http://p2p.wrox.com/sql-server-2000/832-case-where-clause.html</a></p>
<p>Hi everybody<br />
Can I use case statement in WHERE clause.<br />
For example</p>
<p>DECLARE @VAR1 nvarchar(50)<br />
DECLARE @VAR2 nvarchar(50)<br />
SELECT * FROM ORDERS<br />
WHERE CASE @VAR1<br />
          WHEN &#8216;Customers&#8217; THEN CustomerID = @VAR2<br />
          WHEN &#8216;Employee&#8217; THEN EmployeeID = @VAR2<br />
          END</p>
<p>This is not working OK.<br />
Can someone explain me the right way?<br />
Thanks.<br />
Best regards<br />
Alex</p>
<p>&nbsp;</p>
<p>In your situation, where you wish to select on two entirely different columns depending on a parameter, it is probably better to use an IF/ELSE construction, as:</p>
<div>
<div>Code:</div>
<pre>IF @Var1='Customers' THEN
   SELECT * FROM Orders WHERE CustomerID=@Var2;
ELSE
   SELECT * FROM Orders WHERE EmployeeID=@Var2;</pre>
</div>
<p>It&#8217;s important to realize that CASE is an <em>expression</em> and not an executable statement.</p>
<p>The general form of the predicate of a WHERE clause is:</p>
<div>
<div>Code:</div>
<pre> <em>expression</em> operator <em>expression</em></pre>
</div>
<p>where operator is = or &lt;&gt; or &gt; or &lt; etc. The WHERE clause in your query does not follow this form, which is why you were having problems.</p>
<p>If you insist on using the CASE expression, then you can try a couple of ugly alternatives, like:</p>
<div>
<div>Code:</div>
<pre>   SELECT * FROM Orders
    WHERE CustomerID=CASE @Var1 WHEN 'Customers' THEN @Var2 ELSE 0 END
       OR EmployeeID=CASE @Var1 WHEN 'Employees' THEN @Var2 ELSE 0 END</pre>
</div>
<p>assuming that 0 is not a legal value for either &#8216;CustomerID&#8217; or &#8216;EmployeeID&#8217;. You could also try a nested CASE like:</p>
<div>
<div>Code:</div>
<pre>   SELECT * FROM Orders
    WHERE 1 =
      CASE @Var1
         WHEN 'Customers' THEN CASE WHEN CustomerID=@Var2 THEN 1 ELSE 0 END
         WHEN 'Employees' THEN CASE WHEN EmployeeID=@Var2 THEN 1 ELSE 0 END
      END</pre>
</div>
<p>I think that the CASE expression doesn&#8217;t work well in this situation and that the IF/ELSE is simpler and easier to understand.</p>
<p>Jeff Mason<br />
Custom Apps, Inc.<br />
<a href="http://www.custom-apps.com/" target="_blank">www.custom-apps.com</a></p>
<p>I think this should work for you&#8230;</p>
<p>SELECT * FROM ORDERS<br />
WHERE<br />
(<br />
  CASE<br />
    WHEN @VAR1 = &#8216;Customers&#8217; AND CustomerID = @VAR2 THEN 1<br />
    WHEN @VAR1 = &#8216;Employee&#8217; AND EmployeeID = @VAR2 THEN 1<br />
    ELSE 0<br />
  END<br />
) = 1</p>
<p>or you could do this &#8230;</p>
<p>SELECT *<br />
FROM ORDERS<br />
WHERE (@VAR1 = &#8216;Customers&#8217; and CustomerID = @VAR2) OR<br />
      (@VAR1 = &#8216;Employee&#8217; and EmployeeID = @VAR2)</p>
<p>Jeff&#8217;s first answer is best (though it doesn&#8217;t handle an illegal value for @VAR1) and SBacon&#8217;s answer is a close second, but Jeff&#8217;s other answers and Craig&#8217;s answer are all overkill.</p>
<p>Why not just:</p>
<div>
<div>Code:</div>
<pre>DECLARE @VAR1 nvarchar(50)
DECLARE @VAR2 nvarchar(50)
SELECT * FROM ORDERS
WHERE @VAR2 = ( CASE @VAR1
                WHEN 'Customers' THEN CustomerID
                WHEN 'Employee'  THEN EmployeeID
                ELSE -1
                END )</pre>
</div>
<p>The ELSE is in there to protect against an illegal value for @VAR1 of course.<span id="_marker"> </span>Jeff&#8217;s first answer is best (though it doesn&#8217;t handle an illegal value for @VAR1) and SBacon&#8217;s answer is a close second, but Jeff&#8217;s other answers and Craig&#8217;s answer are all overkill.</p>
<p>Why not just:</p>
<div style="margin:5px 20px 20px;">
<div class="smallfont" style="margin-bottom:2px;">Code:</div>
<pre class="alt2" style="text-align:left;width:auto;height:146px;overflow:auto;border:1px inset;margin:0;padding:6px;">DECLARE @VAR1 nvarchar(50)
DECLARE @VAR2 nvarchar(50)
SELECT * FROM ORDERS
WHERE @VAR2 = ( CASE @VAR1
                WHEN 'Customers' THEN CustomerID
                WHEN 'Employee'  THEN EmployeeID
                ELSE -1
                END )</pre>
</div>
<p>The ELSE is in there to protect against an illegal value for @VAR1 of course.</p>
<p>&nbsp;</p>
<div id="post_message_228786">
<div>
<div>Quote:</div>
<table border="0" cellspacing="0" cellpadding="6" width="100%">
<tbody>
<tr>
<td>quote:<em>Originally posted by Old Pedant</em><br />
 &#8230;Jeff&#8217;s other answers &#8230; are all overkill.</td>
</tr>
</tbody>
</table>
</div>
<p>Well&#8230; I did say they were &#8220;&#8230;a couple of ugly alternatives&#8230;&#8221; <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>(Any idea why we&#8217;re responding to a 5 year old original post? <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  )</p>
<p>Jeff Mason<br />
<a href="mailto:je.mason@comcast.net">je.mason@comcast.net</a></div>
<div>&gt; (Any idea why we&#8217;re responding to a 5 year old original post?</p>
<p>Ummm&#8230;because I inanely didn&#8217;t look at the original message date and because SBacon is a complete newbie and how the heck did he *find* this thread in the first place and&#8230; Well, maybe Google sent him this way??? But then why is he responding instead of asking? And&#8230; Ehhh, leave it at &#8220;because I inanely&#8230;&#8221;.</p></div>
Posted in Case When, Where Clause  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/esersahin.wordpress.com/1427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/esersahin.wordpress.com/1427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/esersahin.wordpress.com/1427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/esersahin.wordpress.com/1427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/esersahin.wordpress.com/1427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/esersahin.wordpress.com/1427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/esersahin.wordpress.com/1427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/esersahin.wordpress.com/1427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/esersahin.wordpress.com/1427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/esersahin.wordpress.com/1427/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1427&subd=esersahin&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://esersahin.wordpress.com/2009/11/11/case-in-where-clause/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8e21407efc4fee973e107f07af76dc73?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">DarkStar</media:title>
		</media:content>
	</item>
		<item>
		<title>Windows PowerShell with Sql Server</title>
		<link>http://esersahin.wordpress.com/2009/10/29/windows-powershell-with-sql-server/</link>
		<comments>http://esersahin.wordpress.com/2009/10/29/windows-powershell-with-sql-server/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 13:13:41 +0000</pubDate>
		<dc:creator>esersahin</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Sql Server]]></category>

		<guid isPermaLink="false">http://esersahin.wordpress.com/?p=1422</guid>
		<description><![CDATA[http://www.mssqltips.com/category.asp?catid=81



 




Backup SQL Server Databases with a Windows PowerShell Script
In a previous tip on Backup and Restore SQL Server databases programmatically with SMO, you&#8217;ve seen how you can use Windows PowerShell to backup and restore SQL Server databases. In this tip, I will cover how to use Windows PowerShell to generate SQL Server backups.Generating SQL Scripts [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1422&subd=esersahin&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://www.mssqltips.com/category.asp?catid=81">http://www.mssqltips.com/category.asp?catid=81</a></p>
<table id="table5" border="0" cellspacing="0" cellpadding="5" width="100%">
<tbody>
<tr>
<td width="20" valign="top"> </td>
<td align="left">
<table border="0">
<tbody>
<tr>
<td><a href="http://www.mssqltips.com/tip.asp?tip=1862">Backup SQL Server Databases with a Windows PowerShell Script</a><br />
In a previous tip on Backup and Restore SQL Server databases programmatically with SMO, you&#8217;ve seen how you can use Windows PowerShell to backup and restore SQL Server databases. In this tip, I will cover how to use Windows PowerShell to generate SQL Server backups.<a href="http://www.mssqltips.com/tip.asp?tip=1842">Generating SQL Scripts using Windows PowerShell</a><br />
In a previous tip on SQL Script Generation Programmatically with SMO, you have seen how you can use SMO to generate SQL scripts programmatically. In this tip I will cover how to generate scripts programmatically using Windows PowerShell.</p>
<p><a href="http://www.mssqltips.com/tip.asp?tip=1798">Checking SQL Server Agent jobs using Windows PowerShell </a><br />
Checking for SQL Server Agent jobs and their status is part of your daily task as a DBA. How do we use Windows PowerShell to check for SQL Server Agent jobs?</p>
<p><a href="http://www.mssqltips.com/tip.asp?tip=1784">Check the Last SQL Server Backup Date using Windows PowerShell</a><br />
In a previous tip, Retrieve List of Databases and their Properties using PowerShell, you have seen how you can use Windows PowerShell to audit database properties and use Microsoft Excel to generate a report. Part of the daily SQL Server DBA tasks is to check the backups of all the databases in a SQL Server instance. How do we use Windows PowerShell to check for the last backup date of SQL Server databases and to confirm that they still meet our service level agreement?</p>
<p><a href="http://www.mssqltips.com/tip.asp?tip=1759">Retrieve a List of SQL Server Databases and their Properties using PowerShell</a><br />
In a previous tip on using Using PowerShell with SQL Server Management Objects (SMO), you have seen how you can use Windows PowerShell and SMO to administer SQL Server databases. In this tip I translate some of the Transact-SQL scripts that I use every day to PowerShell scripts, starting with the simple ones like retrieving a list of databases and their properties for auditing purposes.</td>
</tr>
</tbody>
</table>
<table border="0">
<tbody>
<tr>
<td><a href="http://www.mssqltips.com/tip.asp?tip=1745">Using PowerShell with SQL Server Management Objects (SMO)</a><br />
I have been hearing about Microsoft&#8217;s scripting language called Windows PowerShell which is extensively used nowadays for administering and managing Windows servers and workstations. Exchange Server 2007 and Windows Server 2008 are just two of the Microsoft server products that have included this as part of their administrative tools. I want to know how Windows PowerShell can help me as a SQL Server DBA.<a href="http://www.mssqltips.com/tip.asp?tip=1703">Introduction to Windows PowerShell for the SQL Server DBA Part 2</a><br />
I have been hearing about Microsoft&#8217;s scripting language called Windows PowerShell which is extensively used nowadays for administering and managing Windows servers and workstations. Exchange Server 2007 and Windows Server 2008 are just two of the Microsoft server products that have included this as part of their administrative tools. I want to know how Windows PowerShell can help me as a SQL Server DBA.</p>
<p><a href="http://www.mssqltips.com/tip.asp?tip=1684">PowerShell Support in SQL Server 2008 &#8211; Invoke-Sqlcmd Cmdlet</a><br />
In my organization we write scripts to perform all sorts of administrative functions on our many SQL Server instances as well as other server products. We are just getting started with using PowerShell and have heard that SQL Server 2008 provides some built-in support for executing T-SQL commands from within PowerShell. Can you provide some details and examples?</p>
<p><a href="http://www.mssqltips.com/tip.asp?tip=1680">Introduction to Windows PowerShell for the SQL Server DBA Part 1</a><br />
I have been hearing about Microsoft&#8217;s scripting language called Windows PowerShell which is extensively used nowdays for administering and managing Windows servers and workstations. Exchange Server 2007 and Windows Server 2008 are just two of the Microsoft server products that have included this as part of their administrative tools. I want to know how Windows PowerShell can help me as a SQL Server DBA.</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table border="0">
<tbody>
<tr>
<td> </td>
</tr>
</tbody>
</table>
Posted in PowerShell, Sql Server  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/esersahin.wordpress.com/1422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/esersahin.wordpress.com/1422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/esersahin.wordpress.com/1422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/esersahin.wordpress.com/1422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/esersahin.wordpress.com/1422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/esersahin.wordpress.com/1422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/esersahin.wordpress.com/1422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/esersahin.wordpress.com/1422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/esersahin.wordpress.com/1422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/esersahin.wordpress.com/1422/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1422&subd=esersahin&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://esersahin.wordpress.com/2009/10/29/windows-powershell-with-sql-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8e21407efc4fee973e107f07af76dc73?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">DarkStar</media:title>
		</media:content>
	</item>
		<item>
		<title>Backup and Restore SQL Server databases programmatically with SMO</title>
		<link>http://esersahin.wordpress.com/2009/10/29/backup-and-restore-sql-server-databases-programmatically-with-smo/</link>
		<comments>http://esersahin.wordpress.com/2009/10/29/backup-and-restore-sql-server-databases-programmatically-with-smo/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 13:06:56 +0000</pubDate>
		<dc:creator>esersahin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[SQL Server Backup]]></category>
		<category><![CDATA[Sql Server Management Objects]]></category>
		<category><![CDATA[Sql Server Restore]]></category>

		<guid isPermaLink="false">http://esersahin.wordpress.com/?p=1419</guid>
		<description><![CDATA[http://www.mssqltips.com/tip.asp?tip=1849
Problem
In my last set of tips, I discussed SMO at a basic level.  In this tip I am going to provide examples to SQL Server Database Administrators on how to backup and restore SQL Server databases with SMO.  I will start with how you can issue different types (Full, Differential and Log) of backups with [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1419&subd=esersahin&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://www.mssqltips.com/tip.asp?tip=1849">http://www.mssqltips.com/tip.asp?tip=1849</a></p>
<p><span style="text-decoration:underline;"><strong>Problem<br />
</strong></span>In my last set of tips, I discussed SMO at a basic level.  In this tip I am going to provide examples to SQL Server Database Administrators on how to backup and restore SQL Server databases with SMO.  I will start with how you can issue different types (Full, Differential and Log) of backups with SMO and how to restore them when required programmatically using SMO.</p>
<p><strong><span style="text-decoration:underline;">Solution<br />
</span></strong>As I discussed in my last tip, SMO provides utility classes for specific tasks. For backup and restore, it provides two main utility classes (<strong>Backup</strong> and <strong>Restore</strong>) which are available in <strong>Microsoft.SqlServer.Management.Smo</strong> namespace.</p>
<p>Before you start writing SMO code, you need to reference several assemblies which contain the SMO namespaces. For more details on these assemblies and how properly to reference them in your code, refer to my tip <a href="http://www.mssqltips.com/tip.asp?tip=1826">Getting started with SQL Server Management Objects (SMO)</a>.</p>
<p><strong><em>Examples</em></strong></p>
<p><strong>C# Code Block 1 &#8211; Full Backups</strong> &#8211; This example shows how to issue full database backups with SMO. First, create an instance of the <strong>Backup</strong> class and set the associated properties. With the <strong>Action</strong> property you can specify the type of backup such as full, files or log backup. With the <strong>Database</strong> property specify the name of the database being backed up.  The device is the backup media type such as disk or tape, so you need to add a device (one or more) to the <strong>Devices</strong> collection of backup instance. With the <strong>BackupSetName</strong> and <strong>BackupSetDescription</strong> properties you can specify the name and description for the backup set.  The <strong>Backup</strong> class also has a property called <strong>ExpirationDate</strong> which indicates how long backup data is considered valid and to expire the backup after that date. The backup object instance generates several events during the backup operation, we can write event-handlers for these events and wire them up with events. This is what I am doing for progress monitoring.  I am wiring up CompletionStatusInPercent and Backup_Completed methods (event-handlers) with <strong>PercentComplete </strong>and <strong>Complete</strong> events of backup object instance.  Finally, I am calling the <strong>SqlBackup</strong> method for starting up the backup operation, SMO provides a variant of this method called <strong>SqlBackupAsync</strong> if you want to start the backup operation asynchronously.</p>
<table border="1" cellspacing="0" cellpadding="0" width="600">
<tbody>
<tr>
<td><strong>C# Code Block 1 &#8211; Full Database Backup</strong></td>
</tr>
<tr>
<td align="left">Backup bkpDBFull = new Backup();<br />
/* Specify whether you want to back up database or files or log */<br />
bkpDBFull.Action = BackupActionType.Database;<br />
/* Specify the name of the database to back up */<br />
bkpDBFull.Database = myDatabase.Name;<br />
/* You can take backup on several media type (disk or tape), here I am<br />
 * using File type and storing backup on the file system */<br />
bkpDBFull.Devices.AddDevice(@&#8221;D:\AdventureWorksFull.bak&#8221;, DeviceType.File);<br />
bkpDBFull.BackupSetName = &#8220;Adventureworks database Backup&#8221;;<br />
bkpDBFull.BackupSetDescription = &#8220;Adventureworks database &#8211; Full Backup&#8221;;<br />
/* You can specify the expiration date for your backup data<br />
 * after that date backup data would not be relevant */<br />
bkpDBFull.ExpirationDate = DateTime.Today.AddDays(10);<br />
 <br />
/* You can specify Initialize = false (default) to create a new<br />
 * backup set which will be appended as last backup set on the media. You<br />
 * can specify Initialize = true to make the backup as first set on the<br />
 * medium and to overwrite any other existing backup sets if the all the<br />
 * backup sets have expired and specified backup set name matches with<br />
 * the name on the medium */<br />
bkpDBFull.Initialize = false;<br />
 <br />
/* Wiring up events for progress monitoring */<br />
bkpDBFull.PercentComplete += CompletionStatusInPercent;<br />
bkpDBFull.Complete += Backup_Completed;<br />
 <br />
/* SqlBackup method starts to take back up<br />
 * You can also use SqlBackupAsync method to perform the backup<br />
 * operation asynchronously */<br />
bkpDBFull.SqlBackup(myServer);</td>
</tr>
<tr>
<td>private static void CompletionStatusInPercent(object sender, PercentCompleteEventArgs args)<br />
{<br />
    Console.Clear();<br />
    Console.WriteLine(&#8220;Percent completed: {0}%.&#8221;, args.Percent);<br />
}<br />
private static void Backup_Completed(object sender, ServerMessageEventArgs args)<br />
{<br />
    Console.WriteLine(&#8220;Hurray&#8230;Backup completed.&#8221; );<br />
    Console.WriteLine(args.Error.Message);<br />
}<br />
private static void Restore_Completed(object sender, ServerMessageEventArgs args)<br />
{<br />
    Console.WriteLine(&#8220;Hurray&#8230;Restore completed.&#8221;);<br />
    Console.WriteLine(args.Error.Message);<br />
}</td>
</tr>
<tr>
<td><strong>Result:</strong></td>
</tr>
</tbody>
</table>
<p><strong>C# Code Block 2 Differential Backups </strong>- The process of issuing differential backups is not much different from issuing full backups. To issue a differential backup, set the property <strong>Incremental = true</strong>. If you set this property the incremental/differential backup will be taken since last full backup.</p>
<table border="1" cellspacing="0" cellpadding="0" width="600" align="center">
<tbody>
<tr>
<td><strong>C# Code Block 2 &#8211; Differential Database Backup</strong></td>
</tr>
<tr>
<td align="left">Backup bkpDBDifferential = new Backup();<br />
/* Specify whether you want to backup database, files or log */<br />
bkpDBDifferential.Action = BackupActionType.Database;<br />
/* Specify the name of the database to backup */<br />
bkpDBDifferential.Database = myDatabase.Name;<br />
/* You can issue backups on several media types (disk or tape), here I am * using the File type and storing the backup on the file system */<br />
bkpDBDifferential.Devices.AddDevice(@&#8221;D:\AdventureWorksDifferential.bak&#8221;, DeviceType.File);<br />
bkpDBDifferential.BackupSetName = &#8220;Adventureworks database Backup&#8221;;<br />
bkpDBDifferential.BackupSetDescription = &#8220;Adventureworks database &#8211; Differential Backup&#8221;;<br />
/* You can specify the expiration date for your backup data<br />
 * after that date backup data would not be relevant */<br />
bkpDBDifferential.ExpirationDate = DateTime.Today.AddDays(10);<br />
 <br />
/* You can specify Initialize = false (default) to create a new<br />
 * backup set which will be appended as last backup set on the media.<br />
 * You can specify Initialize = true to make the backup as the first set<br />
 * on the medium and to overwrite any other existing backup sets if the<br />
 * backup sets have expired and specified backup set name matches<br />
 * with the name on the medium */<br />
bkpDBDifferential.Initialize = false;<br />
 <br />
/* You can specify Incremental = false (default) to perform full backup<br />
 * or Incremental = true to perform differential backup since most recent<br />
 * full backup */<br />
bkpDBDifferential.Incremental = true;<br />
 <br />
/* Wiring up events for progress monitoring */<br />
bkpDBDifferential.PercentComplete += CompletionStatusInPercent;<br />
bkpDBDifferential.Complete += Backup_Completed;<br />
 <br />
/* SqlBackup method starts to take back up<br />
 * You cab also use SqlBackupAsync method to perform backup<br />
 * operation asynchronously */<br />
bkpDBDifferential.SqlBackup(myServer);</td>
</tr>
<tr>
<td><strong>Result:</strong></td>
</tr>
</tbody>
</table>
<p><strong>C# Code Block 3 Transaction Log Backups </strong>- Again the process of issuing transactional log backup is not much different from issuing full backups. To issue transactional log backups, set the property <strong>Action = BackupActionType.Log</strong> instead of <strong>BackupActionType.Database</strong> as in the case of a full backup.</p>
<table border="1" cellspacing="0" cellpadding="0" width="600" align="center">
<tbody>
<tr>
<td><strong>C# Code Block 3 &#8211; Transaction Log Backup</strong></td>
</tr>
<tr>
<td align="left">Backup bkpDBLog = new Backup();<br />
/* Specify whether you want to back up database or files or log */<br />
bkpDBLog.Action = BackupActionType.Log;<br />
/* Specify the name of the database to back up */<br />
bkpDBLog.Database = myDatabase.Name;<br />
/* You can take backup on several media type (disk or tape), here I am<br />
 * using File type and storing backup on the file system */<br />
bkpDBLog.Devices.AddDevice(@&#8221;D:\AdventureWorksLog.bak&#8221;, DeviceType.File);<br />
bkpDBLog.BackupSetName = &#8220;Adventureworks database Backup&#8221;;<br />
bkpDBLog.BackupSetDescription = &#8220;Adventureworks database &#8211; Log Backup&#8221;;<br />
/* You can specify the expiration date for your backup data<br />
 * after that date backup data would not be relevant */<br />
bkpDBLog.ExpirationDate = DateTime.Today.AddDays(10);<br />
 <br />
/* You can specify Initialize = false (default) to create a new<br />
 * backup set which will be appended as last backup set on the media. You<br />
 * can specify Initialize = true to make the backup as first set on the<br />
 * medium and to overwrite any other existing backup sets if the all the<br />
 * backup sets have expired and specified backup set name matches with<br />
 * the name on the medium */<br />
bkpDBLog.Initialize = false;<br />
 <br />
/* Wiring up events for progress monitoring */<br />
bkpDBLog.PercentComplete += CompletionStatusInPercent;<br />
bkpDBLog.Complete += Backup_Completed;<br />
 <br />
/* SqlBackup method starts to take back up<br />
 * You cab also use SqlBackupAsync method to perform backup<br />
 * operation asynchronously */<br />
bkpDBLog.SqlBackup(myServer);</td>
</tr>
<tr>
<td><strong>Result:</strong></td>
</tr>
</tbody>
</table>
<p><strong>C# Code Block 4 Backup with Compression </strong>- SQL Server 2008 introduces a new feature to issues <a href="http://www.mssqltips.com/tip.asp?tip=1513">backups in a compressed form</a>.  As such, SMO for SQL Server 2008 has been enhanced to support this feature. If you look at the image below you will notice the compressed backup size is almost 25% of full backup, though the level of compression depends on the several factors.</p>
<table border="1" cellspacing="0" cellpadding="0" width="600" align="center">
<tbody>
<tr>
<td><strong>C# Code Block 4 &#8211; Backup with Compression (SQL Server 2008)</strong></td>
</tr>
<tr>
<td align="left">Backup bkpDBFullWithCompression = new Backup();<br />
/* Specify whether you want to back up database or files or log */<br />
bkpDBFullWithCompression.Action = BackupActionType.Database;<br />
/* Specify the name of the database to back up */<br />
bkpDBFullWithCompression.Database = myDatabase.Name;<br />
/* You can use back up compression technique of SQL Server 2008,<br />
 * specify CompressionOption property to On for compressed backup */<br />
bkpDBFullWithCompression.CompressionOption = BackupCompressionOptions.On;<br />
bkpDBFullWithCompression.Devices.AddDevice(@&#8221;D:\AdventureWorksFullWithCompression.bak&#8221;, DeviceType.File);<br />
bkpDBFullWithCompression.BackupSetName = &#8220;Adventureworks database Backup &#8211; Compressed&#8221;;<br />
bkpDBFullWithCompression.BackupSetDescription = &#8220;Adventureworks database &#8211; Full Backup with Compressin &#8211; only in SQL Server 2008&#8243;;<br />
bkpDBFullWithCompression.SqlBackup(myServer);</td>
</tr>
<tr>
<td><strong>Result:</strong></td>
</tr>
</tbody>
</table>
<p><strong>C# Code Block 5 Full or Differential Restores</strong> &#8211; Thus far we have worked through SMO backup examples. Now let&#8217;s change gears to restore with SMO.  SMO provides a <strong>Restore</strong> class to restore a database, similar to the <strong>Backup</strong> class.  With these classes it is necessary to specify the <strong>Action</strong> property to indicate the type of restore i.e. database, files or log.  In a scenario where if you have additional differential or log backups to be restored after it is necessary to specify the <strong>NoRecovery = true</strong> except for the final restore.  In this example, I am wiring up events of the Restore object instance to event-handlers for progress monitoring. Finally the <strong>SqlRestore</strong> method is called to start the restoration. If you want to start the restore operation asynchronously you would need to call <strong>SqlRestoreAsync</strong> method instead.</p>
<table border="1" cellspacing="0" cellpadding="0" width="600" align="center">
<tbody>
<tr>
<td><strong>C# Code Block 5 &#8211; Database Restore &#8211; Full or Differential</strong></td>
</tr>
<tr>
<td align="left">Restore restoreDB = new Restore();<br />
restoreDB.Database = myDatabase.Name;<br />
/* Specify whether you want to restore database, files or log */<br />
restoreDB.Action = RestoreActionType.Database;<br />
restoreDB.Devices.AddDevice(@&#8221;D:\AdventureWorksFull.bak&#8221;, DeviceType.File);<br />
 <br />
/* You can specify ReplaceDatabase = false (default) to not create a new<br />
 * database, the specified database must exist on SQL Server<br />
 * instance. If you can specify ReplaceDatabase = true to create new<br />
 * database image regardless of the existence of specified database with<br />
 * the same name */<br />
restoreDB.ReplaceDatabase = true; <br />
 <br />
/* If you have a differential or log restore after the current restore,<br />
 * you would need to specify NoRecovery = true, this will ensure no<br />
 * recovery performed and subsequent restores are allowed. It means it<br />
 * the database will be in a restoring state. */<br />
restoreDB.NoRecovery = true;<br />
 <br />
/* Wiring up events for progress monitoring */<br />
restoreDB.PercentComplete += CompletionStatusInPercent;<br />
restoreDB.Complete += Restore_Completed;<br />
 <br />
/* SqlRestore method starts to restore the database<br />
 * You can also use SqlRestoreAsync method to perform restore<br />
 * operation asynchronously */<br />
restoreDB.SqlRestore(myServer);</td>
</tr>
<tr>
<td><strong>Result:</strong></td>
</tr>
</tbody>
</table>
<p>To restore a database SQL Server needs to acquire exclusive lock on the database being restored.  If you try to restore a database which is in use, SQL Server will throw the following exception:</p>
<p><strong>C# Code Block 6 Transaction Log Restore</strong> &#8211; The process of restoring a transactional log is similar to restoring a full or differential backup. While restoring a transactional log, it is necessary to set the property <strong>Action = RestoreActionType.Log</strong> instead of <strong>RestoreActionType.Database</strong> as in case of full/differential restore.  Here is an example:</p>
<table border="1" cellspacing="0" cellpadding="0" width="600" align="center">
<tbody>
<tr>
<td><strong>C# Code Block 6 &#8211; Database Restore &#8211; Log</strong></td>
</tr>
<tr>
<td align="left">Restore restoreDBLog = new Restore();<br />
restoreDBLog.Database = myDatabase.Name;<br />
restoreDBLog.Action = RestoreActionType.Log;<br />
restoreDBLog.Devices.AddDevice(@&#8221;D:\AdventureWorksLog.bak&#8221;, DeviceType.File);<br />
 <br />
/* You can specify NoRecovery = false (default) so that transactions are<br />
 * rolled forward and recovered. */<br />
restoreDBLog.NoRecovery = false;<br />
 <br />
/* Wiring up events for progress monitoring */<br />
restoreDBLog.PercentComplete += CompletionStatusInPercent;<br />
restoreDBLog.Complete += Restore_Completed;<br />
 <br />
/* SqlRestore method starts to restore database<br />
 * You cab also use SqlRestoreAsync method to perform restore<br />
 * operation asynchronously */<br />
restoreDBLog.SqlRestore(myServer);</td>
</tr>
<tr>
<td><strong>Result:</strong></td>
</tr>
</tbody>
</table>
<p><strong>C# Code Block 7 Database Restore to a new location</strong> &#8211; At times you need to create a new database and restore to a new physical location which differs from the original database. For that purpose, the <strong>Restore</strong> class has the <strong>RelocateFiles</strong> collection which can be completed for each file with the new location as shown in the code below.</p>
<table border="1" cellspacing="0" cellpadding="0" width="600" align="center">
<tbody>
<tr>
<td><strong>C# Code Block 7 Database Restore &#8211; Different location</strong></td>
</tr>
<tr>
<td align="left">Restore restoreDB = new Restore();<br />
restoreDB.Database = myDatabase.Name + &#8220;New&#8221;;<br />
/* Specify whether you want to restore database or files or log etc */<br />
restoreDB.Action = RestoreActionType.Database;<br />
restoreDB.Devices.AddDevice(@&#8221;D:\AdventureWorksFull.bak&#8221;, DeviceType.File);<br />
 <br />
/* You can specify ReplaceDatabase = false (default) to not create a new<br />
 * database, the specified database must exist on SQL Server instance.<br />
 * You can specify ReplaceDatabase = true to create new database<br />
 * regardless of the existence of specified database */<br />
restoreDB.ReplaceDatabase = true;<br />
 <br />
/* If you have a differential or log restore to be followed, you would<br />
 * specify NoRecovery = true, this will ensure no recovery is done<br />
 * after the restore and subsequent restores are completed. The database<br />
 * would be in a recovered state. */<br />
restoreDB.NoRecovery = false;<br />
 <br />
/* RelocateFiles collection allows you to specify the logical file names<br />
 * and physical file names (new locations) if you want to restore to a<br />
 * different location.*/<br />
restoreDB.RelocateFiles.Add(new RelocateFile(&#8220;AdventureWorks_Data&#8221;, @&#8221;D:\AdventureWorksNew_Data.mdf&#8221;));<br />
restoreDB.RelocateFiles.Add(new RelocateFile(&#8220;AdventureWorks_Log&#8221;, @&#8221;D:\AdventureWorksNew_Log.ldf&#8221;));<br />
 <br />
/* Wiring up events for progress monitoring */<br />
restoreDB.PercentComplete += CompletionStatusInPercent;<br />
restoreDB.Complete += Restore_Completed;<br />
 <br />
/* SqlRestore method starts to restore database<br />
 * You can also use SqlRestoreAsync method to perform restore<br />
 * operation asynchronously */<br />
restoreDB.SqlRestore(myServer);</td>
</tr>
<tr>
<td><strong>Result:</strong><br />
 </td>
</tr>
</tbody>
</table>
<p>Complete code listing (created on SQL Server 2008 and Visual Studio 2008, though there is not much difference if you are using it on SQL Server 2005 and Visual Studio 2005) can be found in the below text box.</p>
<p>using System;<br />
using System.Collections.Generic;<br />
using System.Text;<br />
using Microsoft.SqlServer.Management.Smo;<br />
using Microsoft.SqlServer.Management.Common;<br />
namespace BackupAndRestoreWithSMO2008<br />
{<br />
    class Program<br />
    {<br />
        static void Main(string[] args)<br />
        {<br />
            Server myServer = new Server(@&#8221;ARSHADALI-LAP\ARSHADALI&#8221;);<br />
            try<br />
            {<br />
                //Using windows authentication<br />
                myServer.ConnectionContext.LoginSecure = true;<br />
                myServer.ConnectionContext.Connect();<br />
                Database myDatabase = myServer.Databases["AdventureWorks"];<br />
                BackupDatabaseFull(myServer, myDatabase);<br />
                //BackupDatabaseDifferential(myServer, myDatabase);<br />
                //BackupDatabaseLog(myServer, myDatabase);<br />
                //BackupDatabaseFullWithCompression(myServer, myDatabase);<br />
               <br />
                RestoreDatabase(myServer, myDatabase);<br />
                //RestoreDatabaseLog(myServer, myDatabase);<br />
                //RestoreDatabaseWithDifferentNameAndLocation(myServer, myDatabase);<br />
            }<br />
            catch (Exception ex)<br />
            {<br />
                Console.WriteLine(ex.Message);<br />
                Console.WriteLine(ex.InnerException.Message);<br />
            }<br />
            finally<br />
            {<br />
                if (myServer.ConnectionContext.IsOpen)<br />
                    myServer.ConnectionContext.Disconnect();<br />
                Console.WriteLine(&#8220;Press any key to terminate&#8230;&#8221;);<br />
                Console.ReadKey();<br />
            }<br />
        }<br />
        private static void BackupDatabaseFull(Server myServer, Database myDatabase)<br />
        {<br />
            Backup bkpDBFull = new Backup();<br />
            /* Specify whether you want to back up database or files or log */<br />
            bkpDBFull.Action = BackupActionType.Database;<br />
            /* Specify the name of the database to back up */<br />
            bkpDBFull.Database = myDatabase.Name;<br />
            /* You can take backup on several media type (disk or tape), here I am using<br />
             * File type and storing backup on the file system */<br />
            bkpDBFull.Devices.AddDevice(@&#8221;D:\AdventureWorksFull.bak&#8221;, DeviceType.File);<br />
            bkpDBFull.BackupSetName = &#8220;Adventureworks database Backup&#8221;;<br />
            bkpDBFull.BackupSetDescription = &#8220;Adventureworks database &#8211; Full Backup&#8221;;<br />
            /* You can specify the expiration date for your backup data<br />
             * after that date backup data would not be relevant */<br />
            bkpDBFull.ExpirationDate = DateTime.Today.AddDays(10);<br />
            /* You can specify Initialize = false (default) to create a new<br />
             * backup set which will be appended as last backup set on the media. You can<br />
             * specify Initialize = true to make the backup as first set on the mediuam and<br />
             * to overwrite any other existing backup sets if the all the backup sets have<br />
             * expired and specified backup set name matches with the name on the medium */<br />
            bkpDBFull.Initialize = false;<br />
            /* Wiring up events for progress monitoring */<br />
            bkpDBFull.PercentComplete += CompletionStatusInPercent;<br />
            bkpDBFull.Complete += Backup_Completed;<br />
            /* SqlBackup method starts to take back up<br />
             * You cab also use SqlBackupAsync method to perform backup<br />
             * operation asynchronously */<br />
            bkpDBFull.SqlBackup(myServer);<br />
        }<br />
        private static void BackupDatabaseDifferential(Server myServer, Database myDatabase)<br />
        {<br />
            Backup bkpDBDifferential = new Backup();<br />
            /* Specify whether you want to back up database or files or log */<br />
            bkpDBDifferential.Action = BackupActionType.Database;<br />
            /* Specify the name of the database to back up */<br />
            bkpDBDifferential.Database = myDatabase.Name;<br />
            /* You can take backup on several media type (disk or tape), here I am using<br />
             * File type and storing backup on the file system */<br />
            bkpDBDifferential.Devices.AddDevice(@&#8221;D:\AdventureWorksDifferential.bak&#8221;, DeviceType.File);<br />
            bkpDBDifferential.BackupSetName = &#8220;Adventureworks database Backup&#8221;;<br />
            bkpDBDifferential.BackupSetDescription = &#8220;Adventureworks database &#8211; Differential Backup&#8221;;<br />
            /* You can specify the expiration date for your backup data<br />
             * after that date backup data would not be relevant */<br />
            bkpDBDifferential.ExpirationDate = DateTime.Today.AddDays(10);<br />
            /* You can specify Initialize = false (default) to create a new<br />
             * backup set which will be appended as last backup set on the media. You can<br />
             * specify Initialize = true to make the backup as first set on the mediuam and<br />
             * to overwrite any other existing backup sets if the all the backup sets have<br />
             * expired and specified backup set name matches with the name on the medium */<br />
            bkpDBDifferential.Initialize = false;<br />
            /* You can specify Incremental = false (default) to perform full backup<br />
             * or Incremental = true to perform differential backup since most recent<br />
             * full backup */<br />
            bkpDBDifferential.Incremental = true;<br />
            /* Wiring up events for progress monitoring */<br />
            bkpDBDifferential.PercentComplete += CompletionStatusInPercent;<br />
            bkpDBDifferential.Complete += Backup_Completed;<br />
            /* SqlBackup method starts to take back up<br />
             * You cab also use SqlBackupAsync method to perform backup<br />
             * operation asynchronously */<br />
            bkpDBDifferential.SqlBackup(myServer);<br />
        }<br />
        private static void BackupDatabaseLog(Server myServer, Database myDatabase)<br />
        {<br />
            Backup bkpDBLog = new Backup();<br />
            /* Specify whether you want to back up database or files or log */<br />
            bkpDBLog.Action = BackupActionType.Log;<br />
            /* Specify the name of the database to back up */<br />
            bkpDBLog.Database = myDatabase.Name;<br />
            /* You can take backup on several media type (disk or tape), here I am using<br />
             * File type and storing backup on the file system */<br />
            bkpDBLog.Devices.AddDevice(@&#8221;D:\AdventureWorksLog.bak&#8221;, DeviceType.File);<br />
            bkpDBLog.BackupSetName = &#8220;Adventureworks database Backup&#8221;;<br />
            bkpDBLog.BackupSetDescription = &#8220;Adventureworks database &#8211; Log Backup&#8221;;<br />
            /* You can specify the expiration date for your backup data<br />
             * after that date backup data would not be relevant */<br />
            bkpDBLog.ExpirationDate = DateTime.Today.AddDays(10);<br />
            /* You can specify Initialize = false (default) to create a new<br />
             * backup set which will be appended as last backup set on the media. You can<br />
             * specify Initialize = true to make the backup as first set on the mediuam and<br />
             * to overwrite any other existing backup sets if the all the backup sets have<br />
             * expired and specified backup set name matches with the name on the medium */<br />
            bkpDBLog.Initialize = false;<br />
            /* Wiring up events for progress monitoring */<br />
            bkpDBLog.PercentComplete += CompletionStatusInPercent;<br />
            bkpDBLog.Complete += Backup_Completed;<br />
            /* SqlBackup method starts to take back up<br />
             * You cab also use SqlBackupAsync method to perform backup<br />
             * operation asynchronously */<br />
            bkpDBLog.SqlBackup(myServer);<br />
        }<br />
        private static void BackupDatabaseFullWithCompression(Server myServer, Database myDatabase)<br />
        {<br />
            Backup bkpDBFullWithCompression = new Backup();<br />
            /* Specify whether you want to back up database or files or log */<br />
            bkpDBFullWithCompression.Action = BackupActionType.Database;<br />
            /* Specify the name of the database to back up */<br />
            bkpDBFullWithCompression.Database = myDatabase.Name;<br />
            /* You can use back up compression technique of SQL Server 2008,<br />
             * specify CompressionOption property to On for compressed backup */<br />
            bkpDBFullWithCompression.CompressionOption = BackupCompressionOptions.On;<br />
            bkpDBFullWithCompression.Devices.AddDevice(@&#8221;D:\AdventureWorksFullWithCompression.bak&#8221;, DeviceType.File);<br />
            bkpDBFullWithCompression.BackupSetName = &#8220;Adventureworks database Backup &#8211; Compressed&#8221;;<br />
            bkpDBFullWithCompression.BackupSetDescription = &#8220;Adventureworks database &#8211; Full Backup with Compressin &#8211; only in SQL Server 2008&#8243;;<br />
            bkpDBFullWithCompression.SqlBackup(myServer);<br />
        }<br />
        private static void CompletionStatusInPercent(object sender, PercentCompleteEventArgs args)<br />
        {<br />
            Console.Clear();<br />
            Console.WriteLine(&#8220;Percent completed: {0}%.&#8221;, args.Percent);<br />
        }<br />
        private static void Backup_Completed(object sender, ServerMessageEventArgs args)<br />
        {<br />
            Console.WriteLine(&#8220;Hurray&#8230;Backup completed.&#8221; );<br />
            Console.WriteLine(args.Error.Message);<br />
        }<br />
        private static void Restore_Completed(object sender, ServerMessageEventArgs args)<br />
        {<br />
            Console.WriteLine(&#8220;Hurray&#8230;Restore completed.&#8221;);<br />
            Console.WriteLine(args.Error.Message);<br />
        }<br />
        private static void RestoreDatabase(Server myServer, Database myDatabase)<br />
        {<br />
            Restore restoreDB = new Restore();<br />
            restoreDB.Database = myDatabase.Name;<br />
            /* Specify whether you want to restore database or files or log etc */<br />
            restoreDB.Action = RestoreActionType.Database;<br />
            restoreDB.Devices.AddDevice(@&#8221;D:\AdventureWorksFull.bak&#8221;, DeviceType.File);<br />
            /* You can specify ReplaceDatabase = false (default) to not create a new image<br />
             * of the database, the specified database must exist on SQL Server instance.<br />
             * If you can specify ReplaceDatabase = true to create new database image<br />
             * regardless of the existence of specified database with same name */<br />
            restoreDB.ReplaceDatabase = true;</p>
<p>            /* If you have differential or log restore to be followed, you would need<br />
             * to specify NoRecovery = true, this will ensure no recovery is done after the<br />
             * restore and subsequent restores are allowed. It means it will database<br />
             * in the Restoring state. */<br />
            restoreDB.NoRecovery = true;<br />
            /* Wiring up events for progress monitoring */<br />
            restoreDB.PercentComplete += CompletionStatusInPercent;<br />
            restoreDB.Complete += Restore_Completed;<br />
            /* SqlRestore method starts to restore database<br />
             * You cab also use SqlRestoreAsync method to perform restore<br />
             * operation asynchronously */<br />
            restoreDB.SqlRestore(myServer);<br />
        }<br />
        private static void RestoreDatabaseLog(Server myServer, Database myDatabase)<br />
        {<br />
            Restore restoreDBLog = new Restore();<br />
            restoreDBLog.Database = myDatabase.Name;<br />
            restoreDBLog.Action = RestoreActionType.Log;<br />
            restoreDBLog.Devices.AddDevice(@&#8221;D:\AdventureWorksLog.bak&#8221;, DeviceType.File);<br />
            /* You can specify NoRecovery = false (default) so that transactions are<br />
             * rolled forward and recovered. */<br />
            restoreDBLog.NoRecovery = false;<br />
            /* Wiring up events for progress monitoring */<br />
            restoreDBLog.PercentComplete += CompletionStatusInPercent;<br />
            restoreDBLog.Complete += Restore_Completed;<br />
            /* SqlRestore method starts to restore database<br />
             * You cab also use SqlRestoreAsync method to perform restore<br />
             * operation asynchronously */<br />
            restoreDBLog.SqlRestore(myServer);<br />
        }<br />
        private static void RestoreDatabaseWithDifferentNameAndLocation(Server myServer, Database myDatabase)<br />
        {<br />
            Restore restoreDB = new Restore();<br />
            restoreDB.Database = myDatabase.Name + &#8220;New&#8221;;<br />
            /* Specify whether you want to restore database or files or log etc */<br />
            restoreDB.Action = RestoreActionType.Database;<br />
            restoreDB.Devices.AddDevice(@&#8221;D:\AdventureWorksFull.bak&#8221;, DeviceType.File);<br />
            /* You can specify ReplaceDatabase = false (default) to not create a new image<br />
             * of the database, the specified database must exist on SQL Server instance.<br />
             * You can specify ReplaceDatabase = true to create new database image<br />
             * regardless of the existence of specified database with same name */<br />
            restoreDB.ReplaceDatabase = true;<br />
            /* If you have differential or log restore to be followed, you would need<br />
             * to specify NoRecovery = true, this will ensure no recovery is done after the<br />
             * restore and subsequent restores are allowed. It means it will database<br />
             * in the Restoring state. */<br />
            restoreDB.NoRecovery = false;<br />
            /* RelocateFiles collection allows you to specify the logical file names and<br />
             * physical file names (new locations) if you want to restore to a different location.*/<br />
            restoreDB.RelocateFiles.Add(new RelocateFile(&#8220;AdventureWorks_Data&#8221;, @&#8221;D:\AdventureWorksNew_Data.mdf&#8221;));<br />
            restoreDB.RelocateFiles.Add(new RelocateFile(&#8220;AdventureWorks_Log&#8221;, @&#8221;D:\AdventureWorksNew_Log.ldf&#8221;));<br />
            /* Wiring up events for progress monitoring */<br />
            restoreDB.PercentComplete += CompletionStatusInPercent;<br />
            restoreDB.Complete += Restore_Completed;<br />
            /* SqlRestore method starts to restore database<br />
             * You cab also use SqlRestoreAsync method to perform restore<br />
             * operation asynchronously */<br />
            restoreDB.SqlRestore(myServer);<br />
        }<br />
    }<br />
}</p>
<p><strong><em>Notes:</em></strong></p>
<ul>
<li>Location of assemblies in SQL Server 2005 is the <span style="text-decoration:underline;">C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies</span> folder.</li>
<li>Location of assemblies in SQL Server 2008 is the <span style="text-decoration:underline;">C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies</span> folder.</li>
<li>In SQL Server 2005, the <strong>Backup</strong> and <strong>Restore</strong> classes are available in the <strong>Microsoft.SqlServer.Management.Smo</strong> namespace and in the <strong>Microsoft.SqlServer.Smo</strong> (microsoft.sqlserver.smo.dll) assembly.</li>
<li>In SQL Server 2008, the <strong>Backup</strong> and <strong>Restore</strong> classes are available in the <strong>Microsoft.SqlServer.Management.Smo</strong> namespace and in the <strong>Microsoft.SqlServer.SmoExtended</strong> (microsoft.sqlserver.smoextended.dll) assembly.</li>
<li>If you are restoring a transaction log, you can specify a particular point in time with <strong>ToPointInTime</strong> property of the <strong>Restore</strong> class.</li>
<li>The <strong>Restore</strong> class methods (<strong>SqlVerify</strong>, <strong>SqlVerifyAsync</strong> and <strong>SqlVerifyLatest</strong>) to verify and validate (backup set is complete and the entire backup is readable) the backup media before restoration.</li>
<li>The SQL Server service account must have access to the folders where backup or restore operations are executed.</li>
<li>You need to have sufficient permissions to perform backup and restore operations. For example, for backup you need to be either in sysadmin/db_owner/db_backupoperator role or must have BACKUP DATABASE or BACKUP LOG permission on the database.</li>
<li>If you try to connect SQL Server 2008 from SMO 2005, you will get an exception &#8220;SQL Server &lt;10.0&gt; version is not supported&#8221;.</li>
</ul>
<p><strong><span style="text-decoration:underline;">Next Steps</span></strong></p>
<ul>
<li>Review the following tips:
<ul>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1826">Getting started with SQL Server Management Objects (SMO)</a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1833" target="_blank">SQL Script Generation Programmatically with SMO</a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1513">Exploring Database Backup Compression in SQL Server 2008</a></li>
</ul>
</li>
<li>Review <a href="http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.backup.aspx">Backup</a> and <a href="http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.restore.aspx">Restore</a> classes on MSDN.</li>
<li>Review the MSSQLTips <a href="http://www.mssqltips.com/category.asp?catid=8" target="_blank">Backup and Recovery category</a> with 40+ tips.</li>
</ul>
<p><span style="text-decoration:underline;"><strong>Readers Who Read This Tip Also Read</strong></span></p>
<ul>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1860">How to identify when a database was restored, the source of the backup and the date of the backup</a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1854">How to Backup and Restore a SQL Server FILESTREAM Enabled Database</a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1809">Restore a SQL Server Database to a New Database to Minimize Downtime</a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1779">Mirrored Database Backup Feature in SQL Server 2005 and SQL Server 2008</a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1772">Copy Only Backup for SQL Server 2005 and SQL Server 2008</a></li>
<li><a href="http://www.mssqltips.com/category.asp?catid=8">More&#8230;</a></li>
</ul>
Posted in C#, SQL Server Backup, Sql Server Management Objects, Sql Server Restore  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/esersahin.wordpress.com/1419/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/esersahin.wordpress.com/1419/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/esersahin.wordpress.com/1419/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/esersahin.wordpress.com/1419/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/esersahin.wordpress.com/1419/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/esersahin.wordpress.com/1419/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/esersahin.wordpress.com/1419/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/esersahin.wordpress.com/1419/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/esersahin.wordpress.com/1419/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/esersahin.wordpress.com/1419/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1419&subd=esersahin&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://esersahin.wordpress.com/2009/10/29/backup-and-restore-sql-server-databases-programmatically-with-smo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8e21407efc4fee973e107f07af76dc73?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">DarkStar</media:title>
		</media:content>
	</item>
		<item>
		<title>Using PowerShell with SQL Server Management Objects (SMO)</title>
		<link>http://esersahin.wordpress.com/2009/10/29/using-powershell-with-sql-server-management-objects-smo/</link>
		<comments>http://esersahin.wordpress.com/2009/10/29/using-powershell-with-sql-server-management-objects-smo/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 12:52:07 +0000</pubDate>
		<dc:creator>esersahin</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[Sql Server Management Objects]]></category>

		<guid isPermaLink="false">http://esersahin.wordpress.com/?p=1415</guid>
		<description><![CDATA[http://www.mssqltips.com/tip.asp?tip=1745







Using PowerShell with SQL Server Management Objects (SMO)
Written By: Edwin Sarmiento &#8212; 5/6/2009 &#8212; 2 comments &#8212; printer friendly &#8212; become a member



 






            Free SQL Server Book of Your Choice             



Problem
I have been hearing about Microsoft&#8217;s scripting language called Windows PowerShell which is extensively used nowadays for administering and managing Windows servers and workstations. Exchange Server [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1415&subd=esersahin&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://www.mssqltips.com/tip.asp?tip=1745">http://www.mssqltips.com/tip.asp?tip=1745</a></p>
<table width="100%" bgcolor="#ffffff">
<tbody>
<tr>
<td width="100%" align="left" valign="top">
<table id="table5" border="0" cellspacing="0" cellpadding="5" width="100%">
<tbody>
<tr>
<td valign="middle"><strong><span style="font-size:small;">Using PowerShell with SQL Server Management Objects (SMO)</span></strong><br />
Written By: <a href="http://www.mssqltips.com/author.asp?authorid=18">Edwin Sarmiento</a> &#8212; 5/6/2009 &#8212; <a href="http://blogs.mssqltips.com/forums/t/1394.aspx">2 comments</a> &#8212; <a href="http://www.mssqltips.com/tipprint.asp?tip=1745">printer friendly</a> &#8212; <a href="http://www.mssqltips.com/freesqlservertips.asp?tip">become a member</a></p>
<table id="table3" border="0" cellspacing="0" cellpadding="5" width="100%">
<tbody>
<tr>
<td align="center"> </td>
</tr>
</tbody>
</table>
<table border="0" cellspacing="0" cellpadding="3">
<tbody>
<tr>
<td bgcolor="#bad3f5"><strong><span style="font-family:Arial;font-size:x-small;">            <a href="http://www.mssqltips.com/giveaway.asp?id=20090618htip">Free SQL Server Book of Your Choice</a>             </span></strong></td>
</tr>
</tbody>
</table>
<p><span style="text-decoration:underline;"><strong>Problem<br />
</strong></span>I have been hearing about Microsoft&#8217;s scripting language called Windows PowerShell which is extensively used nowadays for administering and managing Windows servers and workstations. Exchange Server 2007 and Windows Server 2008 are just two of the Microsoft server products that have included this as part of their administrative tools. I want to know how Windows PowerShell can help me as a SQL Server DBA.</p>
<p><span style="text-decoration:underline;"><strong>Solution<br />
</strong></span>To continue this series on Introduction to Windows PowerShell for the SQL Server DBA, this tip will look at writing and running PowerShell scripts. In <a href="http://www.mssqltips.com/tip.asp?tip=1680">Part 1</a>, we have introduced Windows PowerShell, the use of cmdlets and aliases and how we can take full advantage of the help available from the environment. <a href="http://www.mssqltips.com/tip.asp?tip=1703">Part 2</a> talks about using the pipeline and formatting results in PowerShell. In this tip, we will start writing PowerShell scripts and introduce SQL Server Management Objects (SMO).</p>
<p><strong><em>Writing and Running PowerShell scripts </em></strong></p>
<p>Since you can now write a basic command by piping cmdlets in Windows PowerShell, it&#8217;s time to write a script. A script is a sequence of commands and PowerShell cmdlets written together to create more complex tasks. PowerShell script files should have a <strong>.PS1</strong> extension. While you might be wondering about the &#8220;1&#8243; in the file extension, it was intended to be for script versioning. Since PowerShell v2.0 is still in CTP, we are still not sure whether the extension would change, but currently any script with a .PS1 extension will work in PowerShell v2.0.</p>
<p>You can write a script using any text editor like Notepad or TextPad although there are third-party scripting tools out there like <a href="http://www.idera.com/content/show65.aspx" target="_blank">PowerShell Plus</a> from Idera and <a href="http://www.powergui.org/index.jspa" target="_blank">PowerGUI</a> from Quest Software. PowerShell v2.0 CTP comes with a <a href="http://www.microsoft.com/technet/scriptcenter/topics/winpsh/graphical2.mspx" target="_blank">Graphical Windows PowerShell</a> that you can use as your development environment for PowerShell. The choice of a development environment for Windows PowerShell is totally up to you.</p>
<p>&nbsp;</p>
<p>You can start writing scripts by saving the commands you&#8217;ve learned in <a href="http://www.mssqltips.com/tip.asp?tip=1680">Part 1</a> and <a href="http://www.mssqltips.com/tip.asp?tip=1703">Part 2</a> on a <strong>PS1</strong> file. To run the script, you can call it from within Windows PowerShell by specifying either its full or relative path. By default, you wouldn&#8217;t be able to execute scripts in Windows PowerShell due to the security policy.</p>
<p>&nbsp;</p>
<p>To enable a script to run, you have to modify the execution policy within Windows PowerShell by calling the <strong><a href="http://technet.microsoft.com/en-us/library/dd347628.aspx" target="_blank">Set-ExecutionPolicy</a></strong> cmdlet and passing the execution policy as a parameter. Different execution policies are described <a href="http://technet.microsoft.com/en-us/library/dd347641.aspx" target="_blank">here</a>, but the recommended setting is to use <strong>RemoteSigned</strong> as this will allow you to run scripts locally but will require a digital signature from a trusted publisher on scripts that come from a remote source. After setting the execution policy, you can now run your scripts from the PowerShell console</p>
<p>&nbsp;</p>
<p>Notice the period at the beginning of the script together with the backslash? That simply tells PowerShell to execute the script in the current scope. This only means that you have to type the complete file path in order for you to run a script or, in this particular case since the script is in the current directory, you can start it with the&#8221;<strong>.\</strong>&#8221; notation</p>
<p><em><strong>Passing Variable Parameters To A Script</strong></em></p>
<p>In order for your scripts to be dynamic, you have to find ways to pass different values to it. Using parameters with a script allow additional data to be passed to the script in a structured way. You use the <strong>$args[i] </strong>variable to refer to arguments that are passed to a script. The <strong>[i]</strong> simply means that you can use an array of values with an index of <strong>[0]</strong> in case you want to pass multiple parameters to your script. Translating this to the example we used in <a href="http://www.mssqltips.com/tip.asp?tip=1703">Part 2</a>, let&#8217;s say we want the script that returns all the processes with PrivateMemorySize greater than 50MB to be dynamic &#8211; a script that will return all the processes for which property and value we specify. We define variables that will contain the parameters that we will pass to the script and use that variable within the script</p>
<table border="1" cellspacing="0" cellpadding="4" width="100%">
<tbody>
<tr>
<td><span style="font-family:Courier New;font-size:x-small;">#Variable $attrib will contain the values of the first parameter<br />
#Variable $valMB will contain the values of the second parameter<br />
$attrib = $args[0]<br />
$val = $args[1]<br />
Get-Process | Where-Object {$_.$attrib -gt $val} | SELECT ProcessName, $attrib | Format-List </span></td>
</tr>
</tbody>
</table>
<p>Notice the use of the <strong>pound/sharp (#)</strong> symbol to let PowerShell know that the current line is a comment. It is recommended to write as much comments in your scripts as possible. Also, the way to declare a variable in PowerShell starts with a <strong>$</strong> sign. Bear in mind that PowerShell variables are objects, unlike in other scripting languages like VBScript where variables are simply containers for values. This means that you can pass objects to a script variable the same way you can pipe the results of a cmdlet to another cmdlet. The command in the script is exactly the same as what we had in <a href="http://www.mssqltips.com/tip.asp?tip=1703">Part 2</a> with a little variation. We used the variable <strong>$attrib</strong> instead of a fixed property like PrivateMemorySize and the variable <strong>$val</strong> instead of a fixed value</p>
<p>Calling the script and passing parameter values to it:</p>
<p>&nbsp;</p>
<p>Notice how I used PrivateMemorySet and 50MB as the values for <strong>$attrib</strong> and <strong>$val</strong>, respectively, on the first call to the script while using WorkingSet and 100MB on the second call. This makes your script dynamic simply by using variables and parameters.</p>
<p><strong><em>Server Management Objects (SMO): Your Gateway to SQL Server </em></strong></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms162557.aspx" target="_blank">SQL Server Management Objects (SMO)</a> is a collection of objects that are designed for programming all aspects of managing SQL Server. Simply put, its a way to allow programmatic management of SQL Server instances. SQL Server client tools like Management Studio were created using SMO. You can use SMO with other scripting or programming languages that can (note that scripting languages like VBScript uses Component Object Model automation and will not be able to see SMO since it uses .NET) to build SQL Server management applications. While built for SQL Server 2005 using the .NET Framework 2.0, it is compatible with SQL Server 2000 and 2008, allowing you to manage multi-version instances across your enterprise. One thing that you should note though is that SMO does not support compatibility levels below 80. I&#8217;ve seen databases running on SQL Server 2005 but are still on compatibility 70. Hence, you will not be able to manage those databases using SMO.</p>
<p>The first thing you need to do is load the appropriate .NET assemblies used by SMO.</p>
<blockquote><p><strong><em>[System.Reflection.Assembly]::LoadWithPartialName(&#8216;Microsoft.SqlServer.SMO&#8217;) </em></strong></p></blockquote>
<p>You do have to check the versions of the SMO assemblies that you load into memory as this might cause confusion especially when you have multiple versions running on your machine. There are other assemblies that are associated with SMO for managing SQL Server, but most of the time this would suffice. After loading the SMO assemblies, you can now create an instance of the <a href="http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.server.aspx">Server</a> object to represent the SQL Server instance that you will be connecting to, passing the instance name. In the line below, I will be assigning the results to a variable <strong><em>$serverInstanc, </em></strong>so we can manipulate the results the way we have done in the previous examples.</p>
<blockquote><p><strong><em>$serverInstance = New-Object (&#8216;Microsoft.SqlServer.Management.Smo.Server&#8217;) &#8220;InstanceName&#8221; </em></strong></p></blockquote>
<p>You can then pipe the results to the <strong><em>Get-Member</em></strong> cmdlet to see the different properties and methods for the <strong>Server</strong> object.</p>
<p>&nbsp;</p>
<p>One of the most common task we do as SQL Server DBAs is to audit our SQL Server installations. We can apply what we have learned from this tip to write a script to audit our SQL Server installations, retrieving the instance name, the edition, the version and the service pack level.</p>
<table border="1" cellspacing="0" cellpadding="4" width="100%">
<tbody>
<tr>
<td><span style="font-family:Courier New;font-size:x-small;">$instance = $args[0]<br />
[System.Reflection.Assembly]::LoadWithPartialName(&#8216;Microsoft.SqlServer.SMO&#8217;) | out-null<br />
$serverInstance = New-Object (&#8216;Microsoft.SqlServer.Management.Smo.Server&#8217;) $instance </span><span style="font-family:Courier New;font-size:x-small;">Write-Host &#8220;Name: &#8221; $serverInstance.Name<br />
Write-Host &#8220;Edition: &#8221; $serverInstance.Edition<br />
Write-Host &#8220;Version: &#8221; $serverInstance.VersionString<br />
Write-Host &#8220;ProductLevel: &#8221; $serverInstance.ProductLevel </span></td>
</tr>
</tbody>
</table>
<p>I used a few cmdlets in this script for formatting purposes. The <strong><em>Out-Null</em></strong> cmdlet simply deletes the output instead of sending it to the console. We don&#8217;t really need the output but rather we need the object returned by the first line so we just pipe it to the <strong><em>Out-Null</em></strong> cmdlet. Next, I used the <strong><em>Write-Host</em></strong> cmdlet to display the results in the console window for demonstration purposes. You can use the formatting options mentioned in <a href="http://www.mssqltips.com/tip.asp?tip=1703">Part 2</a> to generate a report to be exported in either HTML or CSV. Notice how I used the same script to audit different versions of SQL Server, from 2000 to 2008.</p>
<p>You can also call the <a href="http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.information(SQL.90).aspx" target="_blank">Information</a> class to display all the non-configurable information about the instance you are connecting to. Since we only need a few of them, we just specify them explicitly in the script.</p>
<p><span style="text-decoration:underline;"><strong>Next Steps </strong></span></p>
<p>We have just scratched the tip of the iceberg on PowerShell and SMO. In future tips, we will look at the common DBA tasks and translate them to PowerShell with SMO</p>
<ul>
<li>Download and install Windows PowerShell</li>
<li>Check out the <a href="http://www.microsoft.com/technet/scriptcenter/topics/winpsh/manual/start.mspx" target="_blank">PowerShell Week webcasts</a> from Microsoft TechNet</li>
<li>Read more on the <a href="http://msdn.microsoft.com/en-us/library/cc194731(SQL.90).aspx" target="_blank">SMO Class Library</a> to translate SQL Server objects that we are already familiar with to SMO objects</li>
</ul>
<p><span style="text-decoration:underline;"><strong>Readers Who Read This Tip Also Read</strong></span></p>
<ul>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1862">Backup SQL Server Databases with a Windows PowerShell Script</a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1842">Generating SQL Scripts using Windows PowerShell</a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1798">Checking SQL Server Agent jobs using Windows PowerShell </a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1784">Check the Last SQL Server Backup Date using Windows PowerShell</a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1759">Retrieve a List of SQL Server Databases and their Properties using PowerShell</a></li>
<li><a href="http://www.mssqltips.com/category.asp?catid=81">More&#8230;</a></li>
</ul>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
Posted in PowerShell, Sql Server, Sql Server Management Objects  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/esersahin.wordpress.com/1415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/esersahin.wordpress.com/1415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/esersahin.wordpress.com/1415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/esersahin.wordpress.com/1415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/esersahin.wordpress.com/1415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/esersahin.wordpress.com/1415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/esersahin.wordpress.com/1415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/esersahin.wordpress.com/1415/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/esersahin.wordpress.com/1415/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/esersahin.wordpress.com/1415/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1415&subd=esersahin&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://esersahin.wordpress.com/2009/10/29/using-powershell-with-sql-server-management-objects-smo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8e21407efc4fee973e107f07af76dc73?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">DarkStar</media:title>
		</media:content>
	</item>
		<item>
		<title>Retrieve a List of SQL Server Databases and their Properties using PowerShell</title>
		<link>http://esersahin.wordpress.com/2009/10/29/retrieve-a-list-of-sql-server-databases-and-their-properties-using-powershell/</link>
		<comments>http://esersahin.wordpress.com/2009/10/29/retrieve-a-list-of-sql-server-databases-and-their-properties-using-powershell/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 12:42:50 +0000</pubDate>
		<dc:creator>esersahin</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Sql Server]]></category>

		<guid isPermaLink="false">http://esersahin.wordpress.com/?p=1412</guid>
		<description><![CDATA[http://www.mssqltips.com/tip.asp?tip=1759
Problem
In a previous tip on using Using PowerShell with SQL Server Management Objects (SMO), you&#8217;ve seen how you can use Windows PowerShell and SMO to administer SQL Server databases. I would like to translate some of the Transact-SQL scripts that I use every day, starting with the simple ones like retrieving a list of databases [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1412&subd=esersahin&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://www.mssqltips.com/tip.asp?tip=1759">http://www.mssqltips.com/tip.asp?tip=1759</a></p>
<p><span style="text-decoration:underline;"><strong>Problem<br />
</strong></span>In a previous tip on using <a href="http://www.mssqltips.com/tip.asp?tip=1745">Using PowerShell with SQL Server Management Objects (SMO)</a>, you&#8217;ve seen how you can use Windows PowerShell and SMO to administer SQL Server databases. I would like to translate some of the Transact-SQL scripts that I use every day, starting with the simple ones like retrieving a list of databases and their properties for auditing purposes.</p>
<p><span style="text-decoration:underline;"><strong>Solution</strong></span><br />
One of the things that we do as DBAs is to retrieve a list of databases and their properties for auditing and reporting purposes. We check for properties such as recovery model, available free space, autoshrink, etc., and generate action items based on them. We&#8217;ve already seen how to access the <a href="http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.server.aspx" target="_blank">Server</a> object &#8211; its properties and methods &#8211; using SMO. We will dig into the object hierarchy and look at the different members of the Server object. A SQL Server instance can be described using different properties like instance name, logins, settings, all of which are <a href="http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.server_members(SQL.90).aspx" target="_blank">members</a> of the Server object.</p>
<p>What would be of main interest for this tip is the <a href="http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.server.databases(SQL.90).aspx" target="_blank">Databases</a> property. This property represents a collection of database objects defined on a SQL Server instance, regardless whether they are system or user databases. Let&#8217;s start by retrieving all the members of the <strong>Databases </strong>property. The script below is the same as the one in the previous scripts with the addition of a <strong>Get-Member</strong> cmdlet to retrieve the list of members for the <strong>Databases</strong> property, specifying <strong>Property</strong> as the <strong>MemberType</strong> which just means to retrieve all the database properties. Be sure not to get confused with the terms &#8211; the <strong>Databases</strong> property of the <strong>Server</strong> object is a collection of database objects and the database objects themselves have their own properties.</p>
<table border="1" cellspacing="0" cellpadding="4" width="80%" align="center">
<tbody>
<tr>
<td><span style="font-family:Courier New;font-size:x-small;"><strong>[System.Reflection.Assembly]::LoadWithPartialName(&#8216;Microsoft.SqlServer.SMO&#8217;) | out-null<br />
$s = New-Object (&#8216;Microsoft.SqlServer.Management.Smo.Server&#8217;) &#8220;LOCALHOST\SQL2000&#8243; </strong></span><span style="font-family:Courier New;font-size:x-small;"><strong>$dbs=$s.Databases<br />
$dbs | Get-Member -MemberType Property </strong></span></td>
</tr>
</tbody>
</table>
<p><img src="http://www.mssqltips.com/tipimages2/1759_1.jpg" alt="" /></p>
<p>From the list of properties from the <strong>Database</strong> object, let&#8217;s select the most common ones &#8211; Name, Collation, CompatibilityLevel, AutoShrink, RecoveryModel, Size and SpaceAvailable</p>
<table border="1" cellspacing="0" cellpadding="4" width="80%" align="center">
<tbody>
<tr>
<td><span style="font-family:Courier New;font-size:x-small;"><strong>$dbs | SELECT Name, Collation, CompatibilityLevel, AutoShrink, RecoveryModel, Size, SpaceAvailable</strong></span></td>
</tr>
</tbody>
</table>
<p><img src="http://www.mssqltips.com/tipimages2/1759_2.jpg" alt="" width="634" height="531" /></p>
<p>Notice that it is pretty simple and straight-forward. Since the <strong>$dbs</strong> variable contains a collection of database objects, you can now pipe the results so a <strong>Select-Object</strong> cmdlet, which we just refer to as <strong>SELECT</strong>. You can then make this script dynamic by introducing variables and saving it as a PowerShell script which we have done in previous tips.</p>
<p><em><strong>Reading from a Text File</strong></em></p>
<p>There are a couple of ways to list the servers that you manage, but for simplicity&#8217;s sake, we&#8217;ll use a simple text file. What we will do is store the names of the SQL Server instances that you administer in a text file named <strong>SQL_Servers.txt</strong> and pass the contents in a variable named <strong>$instance</strong>. We will use the <strong><a href="http://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/get-content.mspx" target="_blank">Get-Content</a> </strong>cmdlet to read thru the contents of the text file and the <strong><a href="http://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/foreach-object.mspx" target="_blank">ForEach-Object</a></strong> cmdlet to iterate thru the collection. The script would look something like the one below. You can either write it in a script file or type it directly in the PowerShell console</p>
<table border="1" cellspacing="0" cellpadding="4" width="80%" align="center">
<tbody>
<tr>
<td><span style="font-family:Courier New;font-size:x-small;"><strong>ForEach ($instance in Get-Content &#8220;D:\SQL_Servers.txt&#8221;)</strong><br />
<strong>{</strong><br />
<strong>       [System.Reflection.Assembly]::LoadWithPartialName(&#8216;Microsoft.SqlServer.SMO&#8217;) | out-null<br />
       $s = New-Object (&#8216;Microsoft.SqlServer.Management.Smo.Server&#8217;) $instance </strong></span><span style="font-family:Courier New;font-size:x-small;"><strong>       $dbs=$s.Databases</strong><br />
<strong>       $dbs | SELECT Name, Collation, CompatibilityLevel, AutoShrink, RecoveryModel, Size, SpaceAvailable</strong><br />
<strong>}</strong><br />
</span></td>
</tr>
</tbody>
</table>
<p><img src="http://www.mssqltips.com/tipimages2/1759_3.jpg" alt="" width="633" height="534" /></p>
<p><em><strong>Generate Fancy Reports &#8211; Enter Microsoft Excel </strong></em></p>
<p>Let&#8217;s admit it, Microsoft Excel happens to be the most popular application to generate spreadsheets and reports so it does make sense to make the most out of it with any reports that we need to generate. IT Managers and key stakeholders would like to see either graphs with colors instead of just numerical values within reports. What we will do is to use PowerShell to automate report creation for our database audit report with Excel. There are a few key things that we need to understand about the process. First, we will be calling Excel thru COM automation and not as a .NET application. We used the <strong>New-Object </strong>cmdlet to create an instance of the Excel object, the <strong>-ComObject</strong> parameter to create a new COM object of type<strong> Excel.Application </strong>which is the <strong>ProgID</strong> of the object we want to create and assign it the variable <strong>$Excel</strong>.</p>
<table border="1" cellspacing="0" cellpadding="4" width="79%" align="center">
<tbody>
<tr>
<td><span style="font-family:Courier New;font-size:x-small;"><strong>$Excel = New-Object -ComObject Excel.Application</strong></span></td>
</tr>
</tbody>
</table>
<p>You might be interested to find out what other COM components are available on a Windows machine for you to use. To retrieve their ProgID values, you can query the registry with a one-liner like the one below (this was derived from the <a href="http://blogs.msdn.com/powershell/archive/2009/03/20/get-progid.aspx" target="_blank">PowerShell team blog</a>)</p>
<table border="1" cellspacing="0" cellpadding="4" width="79%" align="center">
<tbody>
<tr>
<td><span style="font-family:Courier New;font-size:x-small;"><strong>dir  &#8221;REGISTRY::HKEY_CLASSES_ROOT\CLSID&#8221; -include PROGID -recurse | foreach {$_.GetValue(&#8220;&#8221;)}</strong></span></td>
</tr>
</tbody>
</table>
<p>So much for COM objects as we only need the Excel.Application at this point. Next, we set the<strong> Visible </strong>property of the Excel object to <strong>True </strong>so we can see what is happening</p>
<table border="1" cellspacing="0" cellpadding="4" width="80%" align="center">
<tbody>
<tr>
<td><span style="font-family:Courier New;font-size:x-small;"><strong>$Excel.visible = $True</strong></span></td>
</tr>
</tbody>
</table>
<p>Next, we use the <strong>Add()</strong> method to add a new workbook to the instance of the Excel object and use the <strong>Item </strong>property to create an object reference to the first worksheet in the workbook. The variable <strong>$Sheet </strong>will hold that pointer to the worksheet and will be referred to in most of the code</p>
<table border="1" cellspacing="0" cellpadding="4" width="79%" align="center">
<tbody>
<tr>
<td><span style="font-family:Courier New;font-size:x-small;"><strong>$Excel = $Excel.Workbooks.Add()</strong><br />
<strong>$Sheet = $Excel.Worksheets.Item(1)</strong></span></td>
</tr>
</tbody>
</table>
<p>You can add as many workbooks as you want, but one would be enough for our purpose. Now, to actually work with Excel we need to reference row and column numbers. To do that, we call the <strong>Cells </strong>property of the Excel object to return the cell or cells in the active sheet. We can then modify the cells like providing a value, changing the Font properties, etc. An example to assign a value to a cell in <strong>row 1, column 1 </strong>and change the <strong>Font </strong>property to <strong>Bold </strong>is shown below.</p>
<table border="1" cellspacing="0" cellpadding="4" width="80%" align="center">
<tbody>
<tr>
<td><span style="font-family:Courier New;font-size:x-small;"><strong>$Sheet.Cells.Item(1,1) = &#8220;SQL SERVER INSTANCE NAME:&#8221;</strong><br />
<strong>$Sheet.Cells.Item(1,1).Font.Bold = $True</strong></span></td>
</tr>
</tbody>
</table>
<p>Saving the code and running it in PowerShell will open up an Excel spreadsheet that will look something like the one below</p>
<p><img src="http://www.mssqltips.com/tipimages2/1759_4.jpg" alt="" width="650" height="279" /></p>
<p>You can either call the <strong>SaveAs() </strong>method of the Worksheet object <strong>$Sheet </strong>to save the Excel spreadsheet or just leave it as it is.</p>
<p>Imagine dealing with row and column values that are dynamic since there would be a fair amount of databases on each of your SQL Server instances. Below is a PowerShell script that takes into account what we have just covered with SMO and Excel to create a fancy report</p>
<table border="1" cellspacing="0" cellpadding="4" width="80%" align="center">
<tbody>
<tr>
<td><span style="font-family:Courier New;font-size:x-small;"><strong>#Create a new Excel object using COM </strong><br />
<strong>$Excel = New-Object -ComObject Excel.Application</strong><br />
<strong>$Excel.visible = $True</strong></span><span style="font-family:Courier New;font-size:x-small;"><strong>$Excel = $Excel.Workbooks.Add()</strong><br />
<strong>$Sheet = $Excel.Worksheets.Item(1)</p>
<p>#Counter variable for rows</strong><br />
<strong>$intRow = 1</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>#Read thru the contents of the SQL_Servers.txt file</strong><br />
<strong>foreach ($instance in get-content &#8220;D:\SQL_Servers.txt&#8221;)</strong><br />
<strong>{</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>     #Create column headers</strong><br />
<strong>     $Sheet.Cells.Item($intRow,1) = &#8220;INSTANCE NAME:&#8221;</strong><br />
<strong>     $Sheet.Cells.Item($intRow,2) = $instance</strong><br />
<strong>     $Sheet.Cells.Item($intRow,1).Font.Bold = $True</strong><br />
<strong>     $Sheet.Cells.Item($intRow,2).Font.Bold = $True</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>     $intRow++</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>      $Sheet.Cells.Item($intRow,1) = &#8220;DATABASE NAME&#8221;</strong><br />
<strong>      $Sheet.Cells.Item($intRow,2) = &#8220;COLLATION&#8221;</strong><br />
<strong>      $Sheet.Cells.Item($intRow,3) = &#8220;COMPATIBILITY LEVEL&#8221;</strong><br />
<strong>      $Sheet.Cells.Item($intRow,4) = &#8220;AUTOSHRINK&#8221;</strong><br />
<strong>      $Sheet.Cells.Item($intRow,5) = &#8220;RECOVERY MODEL&#8221;</strong><br />
<strong>      $Sheet.Cells.Item($intRow,6) = &#8220;SIZE (MB)&#8221;</strong><br />
<strong>      $Sheet.Cells.Item($intRow,7) = &#8220;SPACE AVAILABLE (MB)&#8221;</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>     #Format the column headers</strong><br />
<strong>     for ($col = 1; $col –le 7; $col++)</strong><br />
<strong>     {</strong><br />
<strong>          $Sheet.Cells.Item($intRow,$col).Font.Bold = $True</strong><br />
<strong>          $Sheet.Cells.Item($intRow,$col).Interior.ColorIndex = 48</strong><br />
<strong>          $Sheet.Cells.Item($intRow,$col).Font.ColorIndex = 34</strong><br />
<strong>     }</strong><br />
</span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>     $intRow++</strong><br />
<strong>      #######################################################</strong><br />
<strong>     #This script gets SQL Server database information using PowerShell</strong><br />
</span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>     [System.Reflection.Assembly]::LoadWithPartialName(&#8216;Microsoft.SqlServer.SMO&#8217;) | out-null</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>     # Create an SMO connection to the instance</strong><br />
<strong>     $s = New-Object (&#8216;Microsoft.SqlServer.Management.Smo.Server&#8217;) $instance</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>     $dbs = $s.Databases</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>     #$dbs | SELECT Name, Collation, CompatibilityLevel, AutoShrink, RecoveryModel, Size, SpaceAvailable</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>     #Formatting using Excel</strong> </span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>     ForEach ($db in $dbs)</strong><br />
<strong>     {</p>
<p>          #Divide the value of SpaceAvailable by 1KB<br />
          $dbSpaceAvailable = $db.SpaceAvailable/1KB</p>
<p>          #Format the results to a number with three decimal places </strong><br />
<strong>          $dbSpaceAvailable = &#8220;{0:N3}&#8221; -f $dbSpaceAvailable</strong> </span></p>
<p><span style="font-family:Courier New;font-size:x-small;">          <strong>$Sheet.Cells.Item($intRow, 1) = $db.Name</strong><br />
<strong>          $Sheet.Cells.Item($intRow, 2) = $db.Collation</strong><br />
<strong>          $Sheet.Cells.Item($intRow, 3) = $db.CompatibilityLevel</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>           #Change the background color of the Cell depending on the AutoShrink property value </strong><br />
<strong>           if ($db.AutoShrink -eq &#8220;True&#8221;)</strong><br />
<strong>          {</strong><br />
<strong>               $fgColor = 3</strong><br />
<strong>          }</strong><br />
<strong>          else</strong><br />
<strong>          {</strong><br />
<strong>               $fgColor = 0</strong><br />
<strong>          }</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>          $Sheet.Cells.Item($intRow, 4) = $db.AutoShrink </strong><br />
<strong>          $Sheet.Cells.item($intRow, 4).Interior.ColorIndex = $fgColor</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>          $Sheet.Cells.Item($intRow, 5) = $db.RecoveryModel</strong><br />
<strong>          $Sheet.Cells.Item($intRow, 6) = &#8220;{0:N3}&#8221; -f $db.Size</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>          #Change the background color of the Cell depending on the SpaceAvailable property value<br />
          if ($dbSpaceAvailable -lt 1.00)</strong><br />
<strong>          {</strong><br />
<strong>               $fgColor = 3</strong><br />
<strong>          }</strong><br />
<strong>           else</strong><br />
<strong>          {</strong><br />
<strong>               $fgColor = 0</strong><br />
<strong>          }</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>          $Sheet.Cells.Item($intRow, 7) = $dbSpaceAvailable </strong><br />
<strong>          $Sheet.Cells.item($intRow, 7).Interior.ColorIndex = $fgColor</strong></p>
<p><strong>          $intRow ++</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>     }</strong><br />
</span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>$intRow ++</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>}</strong></span></p>
<p><span style="font-family:Courier New;font-size:x-small;"><strong>$Sheet.UsedRange.EntireColumn.AutoFit()<br />
cls</strong><br />
</span></td>
</tr>
</tbody>
</table>
<p>Running the script in PowerShell will generate an Excel spreadsheet similar to the one below, highlighting those properties that need immediate attention using some fancy colors from the definitions available <a href="http://www.mvps.org/dmcritchie/excel/colors.htm" target="_parent">here</a>.</p>
<p><img src="http://www.mssqltips.com/tipimages2/1759_5.jpg" alt="" width="650" height="511" /></p>
<p><strong><span style="text-decoration:underline;">Next Steps</span><em> </em></strong></p>
<ul>
<li>Download and install Windows PowerShell</li>
<li>Check out the article on <a href="http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept06/hey0908.mspx" target="_blank">How to Use Windows PowerShell to Automate Microsoft Excel</a> from Microsoft TechNet</li>
<li>Read more on the <a href="http://msdn.microsoft.com/en-us/library/cc194731(SQL.90).aspx" target="_blank">SMO Class Library</a> to translate SQL Server objects that we are already familiar with to SMO objects</li>
<li>Find out more about the <a href="http://media.wiley.com/product_ancillary/06/07645566/DOWNLOAD/bapp01.pdf" target="_blank">Excel 2003 Object Model</a> to incorporate it in your automated report generation</li>
</ul>
<p><span style="text-decoration:underline;"><strong>Readers Who Read This Tip Also Read</strong></span></p>
<ul>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1862">Backup SQL Server Databases with a Windows PowerShell Script</a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1842">Generating SQL Scripts using Windows PowerShell</a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1798">Checking SQL Server Agent jobs using Windows PowerShell </a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1784">Check the Last SQL Server Backup Date using Windows PowerShell</a></li>
<li><a href="http://www.mssqltips.com/tip.asp?tip=1745">Using PowerShell with SQL Server Management Objects (SMO)</a></li>
<li><a href="http://www.mssqltips.com/category.asp?catid=81">More&#8230;</a></li>
</ul>
Posted in PowerShell, Sql Server  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/esersahin.wordpress.com/1412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/esersahin.wordpress.com/1412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/esersahin.wordpress.com/1412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/esersahin.wordpress.com/1412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/esersahin.wordpress.com/1412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/esersahin.wordpress.com/1412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/esersahin.wordpress.com/1412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/esersahin.wordpress.com/1412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/esersahin.wordpress.com/1412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/esersahin.wordpress.com/1412/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=esersahin.wordpress.com&blog=1019359&post=1412&subd=esersahin&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://esersahin.wordpress.com/2009/10/29/retrieve-a-list-of-sql-server-databases-and-their-properties-using-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8e21407efc4fee973e107f07af76dc73?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">DarkStar</media:title>
		</media:content>

		<media:content url="http://www.mssqltips.com/tipimages2/1759_1.jpg" medium="image" />

		<media:content url="http://www.mssqltips.com/tipimages2/1759_2.jpg" medium="image" />

		<media:content url="http://www.mssqltips.com/tipimages2/1759_3.jpg" medium="image" />

		<media:content url="http://www.mssqltips.com/tipimages2/1759_4.jpg" medium="image" />

		<media:content url="http://www.mssqltips.com/tipimages2/1759_5.jpg" medium="image" />
	</item>
	</channel>
</rss>