<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="http://code.msdn.microsoft.com/rss.xsl"?><rss version="2.0"><channel><title>SQLExamples Wiki Rss Feed</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Home</link><description>SQLExamples Wiki Rss Description</description><item><title>UPDATED WIKI: WikiGuidelines</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=WikiGuidelines&amp;version=19</link><description>&lt;div class="wikidoc"&gt;
&lt;h5&gt;
MSDN Support Wiki Contributor Guidelines
&lt;/h5&gt; &lt;br /&gt;&lt;ul&gt;
&lt;li&gt;As much as possible, Wiki pages &lt;i&gt;should demonstrate&lt;/i&gt; &lt;b&gt;Best Practices&lt;/b&gt; in Problem and Objective definition, Naming conventions, Formatting, and Descriptive Comments, and always &lt;i&gt;teach by example&lt;/i&gt;. Recognizing that we are all busy and sometimes in our haste we make mistakes and even overlook the obvious, please freely edit and ‘clean up’ anything that that &lt;i&gt;‘just doesn’t look right&lt;/i&gt;. &lt;/li&gt;&lt;li&gt;Any Submission &lt;i&gt;may&lt;/i&gt; be altered, edited, or even removed by any Contibutor. If there is substaintial change, the Original Contributor should be consulted, if possible. We all accept that someone may alter our contribution -it is a contributory Wiki, after all.&lt;/li&gt;&lt;li&gt;All WIKI Page Submissions will have at the bottom, the Original Contributor's Name and Creation Date. Anyone adding significant material to an existing page may add their name adjacent to the new material added.&lt;/li&gt;&lt;li&gt;NO Copyrighted Material &lt;i&gt;should&lt;/i&gt; be posted without consent and attribution, including, if appropriate, a link to the Original Source. A Contributor may freely post his/her own material, and by so doing provides the material under the provisions of the Microsoft Public License (see [License] tab Above). It is ‘best’ to not duplicate material from other sources –but to describe that source and provide a link. For example, a BOL excerpt may change, and if so, then the excerpt would be out of sync. Exceptions ‘might’ include practices that are long standing and/or ANSI standards. We don't want to create a ‘project’ that will require a lot of ongoing maintenance.&lt;/li&gt;&lt;li&gt;It is agreed that this Wiki is NOT to be a 'portal' to send Viewers to Advertiser driven sites. Links to External Sites that require User information, including login accounts, should be carefully considered for the 'value' of the material, as well as to Source's Privacy and Advertising Policies. &lt;/li&gt;&lt;li&gt;Suggested Solutions would be in desending SQL Server Version order; SQL 2008, SQL 2005, SQL 2000 -if the version is applicable to a Solution.&lt;/li&gt;&lt;li&gt;Wiki pages will not be &lt;b&gt;&lt;i&gt;published&lt;/i&gt;&lt;/b&gt; in a incomplete state. If a page is incomplete and still in &lt;i&gt;developemnt&lt;/i&gt;, it should be kept from Public view until complete.&lt;/li&gt;
&lt;/ul&gt; &lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=HowWiki&amp;amp;referringTitle=WikiGuidelines"&gt;How to Create a Wiki Page&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Template&amp;amp;referringTitle=WikiGuidelines"&gt;Wiki Page Template&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=MarkUpGuide&amp;amp;referringTitle=WikiGuidelines"&gt;Guide for Wiki Mark-up&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=TestPage&amp;amp;referringTitle=WikiGuidelines"&gt;Test Environment -A location for Testing&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=TopicList&amp;amp;referringTitle=WikiGuidelines"&gt;Topic Suggestions (and Reservations)&lt;/a&gt;&lt;br /&gt; &lt;br /&gt; &lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt;&lt;i&gt;Page Created By: Arnie Rowland, Mar 13, 2008&lt;/i&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>ArnieRowland</author><pubDate>Wed, 24 Jun 2009 17:42:45 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: WikiGuidelines 20090624P</guid></item><item><title>UPDATED WIKI: WikiGuidelines</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=WikiGuidelines&amp;version=18</link><description>&lt;div class="wikidoc"&gt;
&lt;h5&gt;
MSDN Support Wiki Contributor Guidelines
&lt;/h5&gt; &lt;br /&gt;&lt;ul&gt;
&lt;li&gt;As much as possible, Wiki pages &lt;i&gt;should demonstrate&lt;/i&gt; &lt;b&gt;Best Practices&lt;/b&gt; in Problem and Objective definition, Naming conventions, Formatting, and Descriptive Comments, and always &lt;i&gt;teach by example&lt;/i&gt;. Recognizing that we are all busy and sometimes in our haste we make mistakes and even overlook the obvious, please freely edit and ‘clean up’ anything that that &lt;i&gt;‘just doesn’t look right&lt;/i&gt;. &lt;/li&gt;&lt;li&gt;Any Submission &lt;i&gt;may&lt;/i&gt; be altered, edited, or even removed by any Contibutor. If there is substaintial change, the Original Contributor should be consulted, if possible. We all accept that someone may alter our contribution -it is a contributory Wiki, after all.&lt;/li&gt;&lt;li&gt;All WIKI Page Submissions will have at the bottom, the Original Contributor's Name and Creation Date. Anyone adding significant material to an existing page may add their name adjacent to the new material added.&lt;/li&gt;&lt;li&gt;NO Copyrighted Material &lt;i&gt;should&lt;/i&gt; be posted without consent and attribution, including, if appropriate, a link to the Original Source. A Contributor may freely post his/her own material, and by so doing provides the material under the provisions of the Microsoft Public License (see [License] tab Above). It is ‘best’ to not duplicate material from other sources –but to describe that source and provide a link. For example, a BOL excerpt may change, and if so, then the excerpt would be out of sync. Exceptions ‘might’ include practices that are long standing and/or ANSI standards. We don't want to create a ‘project’ that will require a lot of ongoing maintenance.&lt;/li&gt;&lt;li&gt;It is agreed that this Wiki is NOT to be a 'portal' to send Viewers to Advertiser driven sites. Links to External Sites that require User information, including login accounts, should be carefully considered for the 'value' of the material, as well as to Source's Privacy and Advertising Policies. &lt;/li&gt;&lt;li&gt;Suggested Solutions would be in desending SQL Server Version order; SQL 2008, SQL 2005, SQL 2000 -if the version is applicable to a Solution.&lt;/li&gt;&lt;li&gt;Wiki pages will not be &lt;b&gt;&lt;i&gt;published&lt;/i&gt;&lt;/b&gt; in a incomplete state. If a page is incomplete and still in &lt;i&gt;developemnt&lt;/i&gt;, it should be kept from Public view until complete.&lt;/li&gt;
&lt;/ul&gt; &lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=HowWiki&amp;amp;referringTitle=WikiGuidelines"&gt;How to Create a Wiki Page&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Template&amp;amp;referringTitle=WikiGuidelines"&gt;Wiki Page Template&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=MarkUpGuide&amp;amp;referringTitle=WikiGuidelines"&gt;Guide for Wiki Mark-up&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=TestPage&amp;amp;referringTitle=WikiGuidelines"&gt;Test Environment -A location for Testing&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=TopicList&amp;amp;referringTitle=WikiGuidelines"&gt;Topic Suggestions (and Reservations)&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=MSDN%20Forum%20Moderators%20Guide%3aMicrosoft%20Forums%20Moderation%20Guide.aspx&amp;amp;referringTitle=WikiGuidelines"&gt;MSDN Forum Moderators Guide:Microsoft Forums Moderation Guide.aspx&lt;/a&gt;&lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt;&lt;i&gt;Page Created By: Arnie Rowland, Mar 13, 2008&lt;/i&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>ArnieRowland</author><pubDate>Wed, 24 Jun 2009 16:42:37 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: WikiGuidelines 20090624P</guid></item><item><title>UPDATED WIKI: LastRanDBCCCHECKDBForAllDatabases</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LastRanDBCCCHECKDBForAllDatabases&amp;version=5</link><description>&lt;div class="wikidoc"&gt;
 &lt;br /&gt;At the time of this writing, SQL Server doesn't store the last ran DBCC CHECKDB in the catalog views and there are 2 places from where this information can be pulled out. One is in the SQL Server error logs and the other is the boot page. Paul Randal showed in his blog how to pull this information by looking at the boot page for a given database and this script allows you to see the last ran clean DBCC CHECKDB information in all databases on an instance. &lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
CREATE TABLE #temp (
       Id INT IDENTITY(1,1), 
       ParentObject VARCHAR(255),
       [Object] VARCHAR(255),
       Field VARCHAR(255),
       [Value] VARCHAR(255)
)
 
INSERT INTO #temp
EXECUTE SP_MSFOREACHDB'DBCC DBINFO ( ''?'') WITH TABLERESULTS';
 
;WITH CHECKDB1 AS
(
    SELECT [Value],ROW_NUMBER() OVER (ORDER BY ID) AS rn1 FROM #temp WHERE Field IN ('dbi_dbname'))
    ,CHECKDB2 AS ( SELECT [Value], ROW_NUMBER() OVER (ORDER BY ID) AS rn2 FROM #temp WHERE Field IN ('dbi_dbccLastKnownGood')
)      
SELECT CHECKDB1.Value AS DatabaseName
        , CHECKDB2.Value AS LastRanDBCCCHECKDB
FROM CHECKDB1 JOIN CHECKDB2
ON rn1 =rn2
 
DROP TABLE #temp
&lt;/pre&gt;Acknowledgements: Ward Pond, Paul Randal, Jonathan Kehayias, Aaron Alton.&lt;br /&gt;&lt;a href="http://www.sqlskills.com/BLOGS/PAUL/post/CHECKDB-From-Every-Angle-When-did-DBCC-CHECKDB-last-run-successfully.aspx" class="externalLink"&gt;http://www.sqlskills.com/BLOGS/PAUL/post/CHECKDB-From-Every-Angle-When-did-DBCC-CHECKDB-last-run-successfully.aspx&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>SankarReddy</author><pubDate>Fri, 19 Jun 2009 05:49:38 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: LastRanDBCCCHECKDBForAllDatabases 20090619A</guid></item><item><title>UPDATED WIKI: LastRanDBCCCHECKDBForAllDatabases</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LastRanDBCCCHECKDBForAllDatabases&amp;version=4</link><description>&lt;div class="wikidoc"&gt;
 &lt;br /&gt;At the time of this writing, SQL Server doesn't store the last ran DBCC CHECKDB in the catalog views and there are 2 places from where this information can be pulled out. One is in the SQL Server error logs and the other is the boot page. Paul Randal showed in his blog how to pull this information by looking at the boot page for a given database and this script allows you to see the last ran clean DBCC CHECKDB information in all databases on an instance. &lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
CREATE TABLE #temp (
       Id INT IDENTITY(1,1), 
       ParentObject VARCHAR(255),
       [Object] VARCHAR(255),
       Field VARCHAR(255),
       [Value] VARCHAR(255)
)
 
INSERT INTO #temp
EXECUTE SP_MSFOREACHDB'DBCC DBINFO ( ''?'') WITH TABLERESULTS';
 
;WITH CHECKDB1 AS
(
    SELECT [Value],ROW_NUMBER() OVER (ORDER BY ID) AS rn1 FROM #temp WHERE Field IN ('dbi_dbname'))
    ,CHECKDB2 AS ( SELECT [Value], ROW_NUMBER() OVER (ORDER BY ID) AS rn2 FROM #temp WHERE Field IN ('dbi_dbccLastKnownGood')
)      
SELECT CHECKDB1.Value AS DatabaseName
        , CHECKDB2.Value AS LastRanDBCCCHECKDB
FROM CHECKDB1 JOIN CHECKDB2
ON rn1 =rn2
 
DROP TABLE #temp
&lt;/pre&gt;Acknowledgements: Ward Pond, Paul Randal, Jonathan Kehayias, Aaron Alton.&lt;br /&gt;http://www.sqlskills.com/BLOGS/PAUL/post/CHECKDB-From-Every-Angle-When-did-DBCC-CHECKDB-last-run-successfully.aspx&lt;br /&gt;
&lt;/div&gt;</description><author>SankarReddy</author><pubDate>Tue, 16 Jun 2009 07:04:58 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: LastRanDBCCCHECKDBForAllDatabases 20090616A</guid></item><item><title>UPDATED WIKI: Home</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Home&amp;version=111</link><description>&lt;div class="wikidoc"&gt;
&lt;h3&gt;
Common Solutions for T-SQL Problems
&lt;/h3&gt;&lt;h6&gt;
&lt;i&gt;Information presented in this WIKI represents the suggestions, ideas, and opinions of Volunteer &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ContributorBios&amp;amp;referringTitle=Home"&gt;Moderators and Answerers&lt;/a&gt; who support the Microsoft MSDN SQL Server Forums. (Unless specifically stated otherwise, nothing should be construed to represent the official positions or opinions of Microsoft and/or its Employees.)&lt;/i&gt;
&lt;/h6&gt; &lt;br /&gt;Please direct any additional Questions to the &lt;a href="http://forums.microsoft.com/Forums/default.aspx?ForumGroupID=19&amp;amp;SiteID=1" class="externalLink"&gt;MSDN SQL Server Related Forums&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;How can I &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PrepareQuestion&amp;amp;referringTitle=Home"&gt;Prepare My Question&lt;/a&gt; to Increase the Possibility of Getting a Good Solution?&lt;br /&gt;What are the &lt;a href="http://www.microsoft.com/communities/conduct/default.mspx" class="externalLink"&gt;Rules of Conduct&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt; expected on the Forums?&lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;&lt;i&gt;How To&lt;/i&gt; Examples of Selected T-SQL Programming Constructs&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt; &lt;br /&gt;&lt;b&gt;Data Related Queries&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AlternativesToSQLCursors&amp;amp;referringTitle=Home"&gt;Alternatives To SQL Server Cursors&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AuditOrBypassTriggerExecution&amp;amp;referringTitle=Home"&gt;Audit or Bypass Trigger Execution&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ResultsByRange&amp;amp;referringTitle=Home"&gt;Control Return Results by Range&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=CreateACommaDelimitedList&amp;amp;referringTitle=Home"&gt;Create a Comma Delimited List&lt;/a&gt; from a Column in a Table&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=NumbersTable&amp;amp;referringTitle=Home"&gt;Create and Use A Numbers Table&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PurgeAllTables&amp;amp;referringTitle=Home"&gt;Delete All Data From All User Tables In A Database&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=RecursiveCTE&amp;amp;referringTitle=Home"&gt;Exploring Recursive Common Table Expressions (CTE)&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DuplicateRows&amp;amp;referringTitle=Home"&gt;Find and/or Delete Duplicate Rows&lt;/a&gt; in a Table&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FirstAvailableTimeslot&amp;amp;referringTitle=Home"&gt;Find First Available Timeslot&lt;/a&gt; for Scheduling &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FindDataBetweenDates&amp;amp;referringTitle=Home"&gt;Find Rows of Data Between Two Dates&lt;/a&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FindMissingListItems&amp;amp;referringTitle=Home"&gt;Find the Missing Parts of a List &lt;/a&gt; of Requirements&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Implementation%20of%20DDL%20Trigger%20in%20SQL%20Server%202005&amp;amp;referringTitle=Home"&gt;Implementation of DDL Trigger in SQL Server 2005&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=IncrementAlphaNumericValues&amp;amp;referringTitle=Home"&gt;Increment an AlphaNumeric Value&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ISNULL_COALESCE&amp;amp;referringTitle=Home"&gt;ISNULL() vs. COALESCE()&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=GetAppLock&amp;amp;referringTitle=Home"&gt;Lock a Stored Procedure for Single Use Only&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=StringArrayInput&amp;amp;referringTitle=Home"&gt;Pass and Handle a Delimited String&lt;/a&gt; similar to handling an Array() of Values&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PIVOTData&amp;amp;referringTitle=Home"&gt;PIVOT Data Using T-SQL&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=QueryBasedUponAbsenceOfData&amp;amp;referringTitle=Home"&gt;Queries Based Upon The Absence of Data&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=RankValuesInGroups&amp;amp;referringTitle=Home"&gt;Rank Values in Groups&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=NonDynamicSearch&amp;amp;referringTitle=Home"&gt;Search all or partial columns without Dynamic SQL&lt;/a&gt; while avoiding SQL Injection&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DynamicSearch&amp;amp;referringTitle=Home"&gt;Search all or partial columns with Dynamic SQL&lt;/a&gt; while avoiding SQL Injection&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SelectTopNbyGroup&amp;amp;referringTitle=Home"&gt;SELECT TOP n by Group&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=UNPIVOTData&amp;amp;referringTitle=Home"&gt;UNPIVOT Data Using T-SQL&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;Maintenance Queries&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ExpressBackups&amp;amp;referringTitle=Home"&gt;Automate Backups in SQL Express&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DetachUserDatabases&amp;amp;referringTitle=Home"&gt;Detach All User Databases&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LastBackUpDate&amp;amp;referringTitle=Home"&gt;Find Last BackUp Date Of All Databases On Your Server&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AgentLongRunning&amp;amp;referringTitle=Home"&gt;Find Long Running Agent Jobs&lt;/a&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LongRunningProcs&amp;amp;referringTitle=Home"&gt;Find the TOP n Longest Running Procedures&lt;/a&gt; (or Queries), Ordered by Total Impact on Server &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ExpressMaintenance&amp;amp;referringTitle=Home"&gt;Performing Common Maintenance Tasks in SQL Express&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=TransferLogins&amp;amp;referringTitle=Home"&gt;Transfer Logins to Another Server&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LastRanDBCCCHECKDBForAllDatabases&amp;amp;referringTitle=Home"&gt;Last Ran clean DBCC CHECKDB for all databases&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;Best Practices and Guidelines&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Best%20practices%20%2c%20Design%20and%20Development%20guidelines%20for%20Microsoft%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Best practices , Design and Development guidelines for Microsoft SQL Server&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;SQL Server Maintenance&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AutomatedDBA&amp;amp;referringTitle=Home"&gt;Automating Common DBA Tasks&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SQL2000CDOSysMail&amp;amp;referringTitle=Home"&gt;Configuring SQL Server 2000 Notification with CDOSys&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DatabaseMailConfig&amp;amp;referringTitle=Home"&gt;Configuring SQL Server 2005/2008 Database Mail&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Log%20file%20growth%20in%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Log file growth in SQL Server&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FileSpaceMon&amp;amp;referringTitle=Home"&gt;Monitor free space in the database files&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DiskSpaceMon&amp;amp;referringTitle=Home"&gt;Monitor free space on the server hard disks&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ErrorLogMon&amp;amp;referringTitle=Home"&gt;Monitor the SQL Server Error Log&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LongRunningJobMon&amp;amp;referringTitle=Home"&gt;Monitor long running SQL Agent Jobs&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FailedJobMon&amp;amp;referringTitle=Home"&gt;Monitor failed SQL Agent Jobs&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ServiceStatusMon&amp;amp;referringTitle=Home"&gt;Monitor Service Status&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SystemLogMon&amp;amp;referringTitle=Home"&gt;Monitor System Event Logs&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ProcessInfoMon&amp;amp;referringTitle=Home"&gt;Monitor Running Process Information&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Transfer%20Jobs%20and%20Logins%20using%20SSIS&amp;amp;referringTitle=Home"&gt;Transfer Jobs and Logins using SSIS&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Upgrading%20Steps%20to%20SQL%20Server%202005&amp;amp;referringTitle=Home"&gt;Upgrading Steps to SQL Server 2005&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;SQL Server 2008&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Manage%20unstructured%20data%20using%20FILESTREAM%20Feature%20in%20SQL%20Server%202008&amp;amp;referringTitle=Home"&gt;Manage unstructured data using FILESTREAM Feature in SQL Server 2008&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;&lt;i&gt;How To&lt;/i&gt; Troubleshoot and Debug T-SQL Code&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Troubleshoot%20Deadlocking%20in%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Troubleshoot Deadlocking in SQL Server&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Troubleshoot%20Deadlocking%20in%20SQL%20Server%202005%20using%20Profiler&amp;amp;referringTitle=Home"&gt;Troubleshoot Deadlocking in SQL Server 2005 using Profiler&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DeadlockAnatomy&amp;amp;referringTitle=Home"&gt;Understanding the Anatomy of a Deadlock&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Profiler&amp;amp;referringTitle=Home"&gt;Using the SQL Server Profiler&lt;/a&gt;.&lt;br /&gt; &lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;Writing Transact-SQL Statements Tutorial&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt;&lt;a href="http://msdn2.microsoft.com/en-us/library/ms365303.aspx" class="externalLink"&gt;http://msdn2.microsoft.com/en-us/library/ms365303.aspx&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt;&lt;i&gt;Page Created&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=WikiGuidelines&amp;amp;referringTitle=Home"&gt; &lt;/a&gt;By: Arnie Rowland, Mar 12, 2008&lt;/i&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>SankarReddy</author><pubDate>Tue, 16 Jun 2009 06:59:27 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: Home 20090616A</guid></item><item><title>UPDATED WIKI: LastRanDBCCCHECKDBForAllDatabases</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LastRanDBCCCHECKDBForAllDatabases&amp;version=3</link><description>&lt;div class="wikidoc"&gt;
 &lt;br /&gt;At the time of this writing, SQL Server doesn't store the last ran DBCC CHECKDB in the catalog views and there are 2 places from where this information can be pulled out. One is in the SQL Server error logs and the other is the boot page. Paul Randal showed in his blog how to pull this information by looking at the boot page for a given database and this script allows you to see the last ran clean DBCC CHECKDB information in all databases on an instance. &lt;br /&gt; &lt;br /&gt;CREATE TABLE #temp (&lt;br /&gt;       Id INT IDENTITY(1,1), &lt;br /&gt;       ParentObject VARCHAR(255),&lt;br /&gt;       &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Object&amp;amp;referringTitle=LastRanDBCCCHECKDBForAllDatabases"&gt;Object&lt;/a&gt; VARCHAR(255),&lt;br /&gt;       Field VARCHAR(255),&lt;br /&gt;       &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Value&amp;amp;referringTitle=LastRanDBCCCHECKDBForAllDatabases"&gt;Value&lt;/a&gt; VARCHAR(255)&lt;br /&gt;)&lt;br /&gt; &lt;br /&gt;INSERT INTO #temp&lt;br /&gt;EXECUTE SP_MSFOREACHDB'DBCC DBINFO ( ''?'') WITH TABLERESULTS';&lt;br /&gt; &lt;br /&gt;;WITH CHECKDB1 AS&lt;br /&gt;(&lt;br /&gt;    SELECT &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Value&amp;amp;referringTitle=LastRanDBCCCHECKDBForAllDatabases"&gt;Value&lt;/a&gt;,ROW&lt;i&gt;NUMBER() OVER (ORDER BY ID) AS rn1 FROM #temp WHERE Field IN ('dbi&lt;/i&gt;dbname'))&lt;br /&gt;    ,CHECKDB2 AS ( SELECT &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Value&amp;amp;referringTitle=LastRanDBCCCHECKDBForAllDatabases"&gt;Value&lt;/a&gt;, ROW&lt;i&gt;NUMBER() OVER (ORDER BY ID) AS rn2 FROM #temp WHERE Field IN ('dbi&lt;/i&gt;dbccLastKnownGood')&lt;br /&gt;)      &lt;br /&gt;SELECT CHECKDB1.Value AS DatabaseName&lt;br /&gt;        , CHECKDB2.Value AS LastRanDBCCCHECKDB&lt;br /&gt;FROM CHECKDB1 JOIN CHECKDB2&lt;br /&gt;ON rn1 =rn2&lt;br /&gt; &lt;br /&gt;DROP TABLE #temp&lt;br /&gt; &lt;br /&gt;Acknowledgements: Ward Pond, Paul Randal, Jonathan Kehayias, Aaron Alton.&lt;br /&gt;http://www.sqlskills.com/BLOGS/PAUL/post/CHECKDB-From-Every-Angle-When-did-DBCC-CHECKDB-last-run-successfully.aspx&lt;br /&gt;
&lt;/div&gt;</description><author>SankarReddy</author><pubDate>Tue, 16 Jun 2009 06:55:05 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: LastRanDBCCCHECKDBForAllDatabases 20090616A</guid></item><item><title>UPDATED WIKI: LastRanDBCCCHECKDBForAllDatabases</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LastRanDBCCCHECKDBForAllDatabases&amp;version=2</link><description>&lt;div class="wikidoc"&gt;
 &lt;br /&gt;At the time of this writing, SQL Server doesn't store the last ran DBCC CHECKDB in the catalog views and there are 2 places from where this information can be pulled out. One is in the SQL Server error logs and the other is the boot page. Paul Randal showed in his blog how to pull this information by looking at the boot page for a given database and this script allows you to see the last ran clean DBCC CHECKDB information in all databases on an instance. &lt;br /&gt; &lt;br /&gt;CREATE TABLE #temp (&lt;br /&gt;       Id INT IDENTITY(1,1), &lt;br /&gt;       ParentObject VARCHAR(255),&lt;br /&gt;       &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Object&amp;amp;referringTitle=LastRanDBCCCHECKDBForAllDatabases"&gt;Object&lt;/a&gt; VARCHAR(255),&lt;br /&gt;       Field VARCHAR(255),&lt;br /&gt;       &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Value&amp;amp;referringTitle=LastRanDBCCCHECKDBForAllDatabases"&gt;Value&lt;/a&gt; VARCHAR(255)&lt;br /&gt;)&lt;br /&gt; &lt;br /&gt;INSERT INTO #temp&lt;br /&gt;EXECUTE SP_MSFOREACHDB'DBCC DBINFO ( ''?'') WITH TABLERESULTS';&lt;br /&gt; &lt;br /&gt;;WITH CHECKDB1 AS&lt;br /&gt;(&lt;br /&gt;    SELECT &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Value&amp;amp;referringTitle=LastRanDBCCCHECKDBForAllDatabases"&gt;Value&lt;/a&gt;,ROW&lt;i&gt;NUMBER() OVER (ORDER BY ID) AS rn1 FROM #temp WHERE Field IN ('dbi&lt;/i&gt;dbname'))&lt;br /&gt;    ,CHECKDB2 AS ( SELECT &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Value&amp;amp;referringTitle=LastRanDBCCCHECKDBForAllDatabases"&gt;Value&lt;/a&gt;, ROW&lt;i&gt;NUMBER() OVER (ORDER BY ID) AS rn2 FROM #temp WHERE Field IN ('dbi&lt;/i&gt;dbccLastKnownGood')&lt;br /&gt;)      &lt;br /&gt;SELECT CHECKDB1.Value AS DatabaseName&lt;br /&gt;        , CHECKDB2.Value AS LastRanDBCCCHECKDB&lt;br /&gt;FROM CHECKDB1 JOIN CHECKDB2&lt;br /&gt;ON rn1 =rn2&lt;br /&gt; &lt;br /&gt;DROP TABLE #temp&lt;br /&gt; &lt;br /&gt;Acknowledgements: Ward Pond, Paul Randal, Jonathan Kehayias, Aaron Alton.&lt;br /&gt;http://www.sqlskills.com/BLOGS/PAUL/post/CHECKDB-From-Every-Angle-When-did-DBCC-CHECKDB-last-run-successfully.aspx&lt;br /&gt;
&lt;/div&gt;</description><author>SankarReddy</author><pubDate>Tue, 16 Jun 2009 06:49:54 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: LastRanDBCCCHECKDBForAllDatabases 20090616A</guid></item><item><title>UPDATED WIKI: LastRanDBCCCHECKDBForAllDatabases</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LastRanDBCCCHECKDBForAllDatabases&amp;version=1</link><description>&lt;div class="wikidoc"&gt;
 &lt;br /&gt;At the time of this writing, SQL Server doesn't store the last ran DBCC CHECKDB in the catalog views and there are 2 places from where this information can be pulled out. One is in the SQL Server error logs and the other is the boot page. Paul Randal showed in his blog how to pull this information by looking at the boot page for a given database and this script allows you to see the last ran clean DBCC CHECKDB information in all databases on an instance. &lt;br /&gt; &lt;br /&gt;CREATE TABLE #temp (&lt;br /&gt;       Id INT IDENTITY(1,1), &lt;br /&gt;       ParentObject VARCHAR(255),&lt;br /&gt;       &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Object&amp;amp;referringTitle=LastRanDBCCCHECKDBForAllDatabases"&gt;Object&lt;/a&gt; VARCHAR(255),&lt;br /&gt;       Field VARCHAR(255),&lt;br /&gt;       &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Value&amp;amp;referringTitle=LastRanDBCCCHECKDBForAllDatabases"&gt;Value&lt;/a&gt; VARCHAR(255)&lt;br /&gt;)&lt;br /&gt; &lt;br /&gt;INSERT INTO #temp&lt;br /&gt;EXECUTE SP_MSFOREACHDB'DBCC DBINFO ( ''?'') WITH TABLERESULTS';&lt;br /&gt; &lt;br /&gt;;WITH CHECKDB1 AS&lt;br /&gt;(&lt;br /&gt;    SELECT &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Value&amp;amp;referringTitle=LastRanDBCCCHECKDBForAllDatabases"&gt;Value&lt;/a&gt;,ROW&lt;i&gt;NUMBER() OVER (ORDER BY ID) AS rn1 FROM #temp WHERE Field IN ('dbi&lt;/i&gt;dbname'))&lt;br /&gt;    ,CHECKDB2 AS ( SELECT &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Value&amp;amp;referringTitle=LastRanDBCCCHECKDBForAllDatabases"&gt;Value&lt;/a&gt;, ROW&lt;i&gt;NUMBER() OVER (ORDER BY ID) AS rn2 FROM #temp WHERE Field IN ('dbi&lt;/i&gt;dbccLastKnownGood')&lt;br /&gt;)      &lt;br /&gt;SELECT CHECKDB1.Value AS DatabaseName&lt;br /&gt;        , CHECKDB2.Value AS LastRanDBCCCHECKDB&lt;br /&gt;FROM CHECKDB1 JOIN CHECKDB2&lt;br /&gt;ON rn1 =rn2&lt;br /&gt; &lt;br /&gt;DROP TABLE #temp&lt;br /&gt;
&lt;/div&gt;</description><author>SankarReddy</author><pubDate>Tue, 16 Jun 2009 06:47:33 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: LastRanDBCCCHECKDBForAllDatabases 20090616A</guid></item><item><title>UPDATED WIKI: Home</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Home&amp;version=110</link><description>&lt;div class="wikidoc"&gt;
&lt;h3&gt;
Common Solutions for T-SQL Problems
&lt;/h3&gt;&lt;h6&gt;
&lt;i&gt;Information presented in this WIKI represents the suggestions, ideas, and opinions of Volunteer &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ContributorBios&amp;amp;referringTitle=Home"&gt;Moderators and Answerers&lt;/a&gt; who support the Microsoft MSDN SQL Server Forums. (Unless specifically stated otherwise, nothing should be construed to represent the official positions or opinions of Microsoft and/or its Employees.)&lt;/i&gt;
&lt;/h6&gt; &lt;br /&gt;Please direct any additional Questions to the &lt;a href="http://forums.microsoft.com/Forums/default.aspx?ForumGroupID=19&amp;amp;SiteID=1" class="externalLink"&gt;MSDN SQL Server Related Forums&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;How can I &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PrepareQuestion&amp;amp;referringTitle=Home"&gt;Prepare My Question&lt;/a&gt; to Increase the Possibility of Getting a Good Solution?&lt;br /&gt;What are the &lt;a href="http://www.microsoft.com/communities/conduct/default.mspx" class="externalLink"&gt;Rules of Conduct&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt; expected on the Forums?&lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;&lt;i&gt;How To&lt;/i&gt; Examples of Selected T-SQL Programming Constructs&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt; &lt;br /&gt;&lt;b&gt;Data Related Queries&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AlternativesToSQLCursors&amp;amp;referringTitle=Home"&gt;Alternatives To SQL Server Cursors&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AuditOrBypassTriggerExecution&amp;amp;referringTitle=Home"&gt;Audit or Bypass Trigger Execution&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ResultsByRange&amp;amp;referringTitle=Home"&gt;Control Return Results by Range&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=CreateACommaDelimitedList&amp;amp;referringTitle=Home"&gt;Create a Comma Delimited List&lt;/a&gt; from a Column in a Table&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=NumbersTable&amp;amp;referringTitle=Home"&gt;Create and Use A Numbers Table&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PurgeAllTables&amp;amp;referringTitle=Home"&gt;Delete All Data From All User Tables In A Database&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=RecursiveCTE&amp;amp;referringTitle=Home"&gt;Exploring Recursive Common Table Expressions (CTE)&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DuplicateRows&amp;amp;referringTitle=Home"&gt;Find and/or Delete Duplicate Rows&lt;/a&gt; in a Table&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FirstAvailableTimeslot&amp;amp;referringTitle=Home"&gt;Find First Available Timeslot&lt;/a&gt; for Scheduling &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FindDataBetweenDates&amp;amp;referringTitle=Home"&gt;Find Rows of Data Between Two Dates&lt;/a&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FindMissingListItems&amp;amp;referringTitle=Home"&gt;Find the Missing Parts of a List &lt;/a&gt; of Requirements&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Implementation%20of%20DDL%20Trigger%20in%20SQL%20Server%202005&amp;amp;referringTitle=Home"&gt;Implementation of DDL Trigger in SQL Server 2005&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=IncrementAlphaNumericValues&amp;amp;referringTitle=Home"&gt;Increment an AlphaNumeric Value&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ISNULL_COALESCE&amp;amp;referringTitle=Home"&gt;ISNULL() vs. COALESCE()&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=GetAppLock&amp;amp;referringTitle=Home"&gt;Lock a Stored Procedure for Single Use Only&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=StringArrayInput&amp;amp;referringTitle=Home"&gt;Pass and Handle a Delimited String&lt;/a&gt; similar to handling an Array() of Values&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PIVOTData&amp;amp;referringTitle=Home"&gt;PIVOT Data Using T-SQL&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=QueryBasedUponAbsenceOfData&amp;amp;referringTitle=Home"&gt;Queries Based Upon The Absence of Data&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=RankValuesInGroups&amp;amp;referringTitle=Home"&gt;Rank Values in Groups&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=NonDynamicSearch&amp;amp;referringTitle=Home"&gt;Search all or partial columns without Dynamic SQL&lt;/a&gt; while avoiding SQL Injection&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DynamicSearch&amp;amp;referringTitle=Home"&gt;Search all or partial columns with Dynamic SQL&lt;/a&gt; while avoiding SQL Injection&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SelectTopNbyGroup&amp;amp;referringTitle=Home"&gt;SELECT TOP n by Group&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=UNPIVOTData&amp;amp;referringTitle=Home"&gt;UNPIVOT Data Using T-SQL&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;Maintenance Queries&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ExpressBackups&amp;amp;referringTitle=Home"&gt;Automate Backups in SQL Express&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DetachUserDatabases&amp;amp;referringTitle=Home"&gt;Detach All User Databases&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LastBackUpDate&amp;amp;referringTitle=Home"&gt;Find Last BackUp Date Of All Databases On Your Server&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AgentLongRunning&amp;amp;referringTitle=Home"&gt;Find Long Running Agent Jobs&lt;/a&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LongRunningProcs&amp;amp;referringTitle=Home"&gt;Find the TOP n Longest Running Procedures&lt;/a&gt; (or Queries), Ordered by Total Impact on Server &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ExpressMaintenance&amp;amp;referringTitle=Home"&gt;Performing Common Maintenance Tasks in SQL Express&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=TransferLogins&amp;amp;referringTitle=Home"&gt;Transfer Logins to Another Server&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;Best Practices and Guidelines&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Best%20practices%20%2c%20Design%20and%20Development%20guidelines%20for%20Microsoft%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Best practices , Design and Development guidelines for Microsoft SQL Server&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;SQL Server Maintenance&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AutomatedDBA&amp;amp;referringTitle=Home"&gt;Automating Common DBA Tasks&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SQL2000CDOSysMail&amp;amp;referringTitle=Home"&gt;Configuring SQL Server 2000 Notification with CDOSys&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DatabaseMailConfig&amp;amp;referringTitle=Home"&gt;Configuring SQL Server 2005/2008 Database Mail&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Log%20file%20growth%20in%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Log file growth in SQL Server&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FileSpaceMon&amp;amp;referringTitle=Home"&gt;Monitor free space in the database files&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DiskSpaceMon&amp;amp;referringTitle=Home"&gt;Monitor free space on the server hard disks&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ErrorLogMon&amp;amp;referringTitle=Home"&gt;Monitor the SQL Server Error Log&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LongRunningJobMon&amp;amp;referringTitle=Home"&gt;Monitor long running SQL Agent Jobs&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FailedJobMon&amp;amp;referringTitle=Home"&gt;Monitor failed SQL Agent Jobs&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ServiceStatusMon&amp;amp;referringTitle=Home"&gt;Monitor Service Status&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SystemLogMon&amp;amp;referringTitle=Home"&gt;Monitor System Event Logs&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ProcessInfoMon&amp;amp;referringTitle=Home"&gt;Monitor Running Process Information&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Transfer%20Jobs%20and%20Logins%20using%20SSIS&amp;amp;referringTitle=Home"&gt;Transfer Jobs and Logins using SSIS&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Upgrading%20Steps%20to%20SQL%20Server%202005&amp;amp;referringTitle=Home"&gt;Upgrading Steps to SQL Server 2005&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;SQL Server 2008&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Manage%20unstructured%20data%20using%20FILESTREAM%20Feature%20in%20SQL%20Server%202008&amp;amp;referringTitle=Home"&gt;Manage unstructured data using FILESTREAM Feature in SQL Server 2008&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;&lt;i&gt;How To&lt;/i&gt; Troubleshoot and Debug T-SQL Code&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Troubleshoot%20Deadlocking%20in%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Troubleshoot Deadlocking in SQL Server&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Troubleshoot%20Deadlocking%20in%20SQL%20Server%202005%20using%20Profiler&amp;amp;referringTitle=Home"&gt;Troubleshoot Deadlocking in SQL Server 2005 using Profiler&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DeadlockAnatomy&amp;amp;referringTitle=Home"&gt;Understanding the Anatomy of a Deadlock&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Profiler&amp;amp;referringTitle=Home"&gt;Using the SQL Server Profiler&lt;/a&gt;.&lt;br /&gt; &lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;Writing Transact-SQL Statements Tutorial&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt;&lt;a href="http://msdn2.microsoft.com/en-us/library/ms365303.aspx" class="externalLink"&gt;http://msdn2.microsoft.com/en-us/library/ms365303.aspx&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt;&lt;i&gt;Page Created&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=WikiGuidelines&amp;amp;referringTitle=Home"&gt; &lt;/a&gt;By: Arnie Rowland, Mar 12, 2008&lt;/i&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>AaronAlton</author><pubDate>Wed, 10 Dec 2008 04:58:28 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: Home 20081210A</guid></item><item><title>UPDATED WIKI: AlternativesToSQLCursors</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AlternativesToSQLCursors&amp;version=3</link><description>&lt;div class="wikidoc"&gt;
&lt;h3&gt;
Alternatives To SQL Server Cursors
&lt;/h3&gt;&lt;h6&gt;
&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ContributorBios&amp;amp;referringTitle=AlternativesToSQLCursors&amp;amp;ANCHOR#AaronAlton"&gt;Aaron Alton&lt;/a&gt;, December 2008
&lt;/h6&gt; &lt;br /&gt;&lt;h4&gt;
Introduction
&lt;/h4&gt;Anyone with more than a little exposure to SQL Server will soon come to the conclusion that the use of cursors is best avoided.  SQL Server is a &lt;a href="http://en.wikipedia.org/wiki/RDBMS" class="externalLink"&gt;Relational Database Management System&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;, and as such is very proficient at processing sets of data.  The use of a cursor effectively repeats an operation once for each row being processed, thereby consuming far more server resources than would be necessitated by a set-based operation.  In addition, since SQL cursors are processed much more slowly than set-based operations, any locks generated by the use of said cursor are held longer than would otherwise be necessary.  In this way, the use of a cursor can affect not only the performance of a given batch of work, but also the performance of any other batches which need to make use of the same data resources.&lt;br /&gt; &lt;br /&gt;In order to effectively avoid using a SQL cursor, one must know why a cursor is being used in the first place.  The list below details the most common reasons why people use cursors, and some possible solutions for each problem.&lt;br /&gt; &lt;br /&gt;&lt;a href="#Test_Data"&gt;Test Data&lt;/a&gt;&lt;br /&gt;&lt;a href="#NewToSQL"&gt;Problem: The Developer or Designer is new to SQL Server&lt;/a&gt;&lt;br /&gt;&lt;a href="#UpdateWithRowKey"&gt;Problem: Need to update a table with incrementing column values for records already in the table&lt;/a&gt;&lt;br /&gt;&lt;a href="#CustomIdentityFunctions"&gt;Problem: Need to use a custom identity function to perform an insert&lt;/a&gt;&lt;br /&gt;&lt;a href="#CompareAdjacentRows"&gt;Problem: Need to compare a row to adjacent rows in a table&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;a name="NewToSQL"&gt;&lt;/a&gt;&lt;br /&gt;&lt;h5&gt;
Test Data:
&lt;/h5&gt;The following test data is used for each of the resolutions below.&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
USE AdventureWorks;
 
--Set up test data
IF (SELECT OBJECT_ID('HumanResources.EmployeeLogins')) IS NOT NULL
BEGIN
	DROP TABLE HumanResources.EmployeeLogins
END
 
CREATE TABLE HumanResources.EmployeeLogins 
	(RowKey		int NULL,
	LoginID		nvarchar(256) NOT NULL);
 
INSERT HumanResources.EmployeeLogins (LoginID)
SELECT LoginID FROM HumanResources.Employee
 
INSERT HumanResources.EmployeeLogins (LoginID)
SELECT 'Skunk-Works' + RIGHT(LoginID, LEN(LoginID) - CHARINDEX('\', LoginID) + 1)
FROM   HumanResources.Employee
&lt;/pre&gt;This test data is somewhat contrived, however it is an accessible example for anyone who has AdventureWorks installed.&lt;br /&gt; &lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
Problem: The Developer or Designer is New to SQL Server 
&lt;/h5&gt;By far, this is the most common reason for cursor usage.  If a programmer is already well versed in an event-driven programming language such as Visual Basic, they will possess a great wealth of experience in dealing with data items one at a time.  As such, their natural inclination when moving into SQL is to do the same.  Unfortunately, what is appropriate in one language may be (and in this case is) entirely inappropriate in another.  &lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
Resolution
&lt;/h5&gt;The primary weapon against cursor usage in this scenario is to develop a strong understanding of the basics of Transact-SQL.  There are countless courses, books, and websites dedicated to the topic.  In addition, you can review the examples below, which present set-based solutions to problems which may otherwise necessitate a cursor.&lt;br /&gt;If you’re still struggling with finding a set-based solution, post a question in the &lt;a href="http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=85&amp;amp;SiteID=1" class="externalLink"&gt;MSDN Transact-SQL Forum&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;.  Before doing so, review Arnie Rowland’s article on &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PrepareQuestion&amp;amp;referringTitle=AlternativesToSQLCursors"&gt;how to prepare your question to increase the possibility of eliciting a suitable solution&lt;/a&gt;.&lt;br /&gt; &lt;br /&gt; &lt;br /&gt;&lt;a name="UpdateWithRowKey"&gt;&lt;/a&gt;&lt;br /&gt;&lt;h5&gt;
Problem: Need to update a table with incrementing column values for records already in the table
&lt;/h5&gt;This problem is most often encountered when importing data from an external data source.  The external data source may not have a key field, for instance, and for one of various reasons, an identity column cannot be used while importing. &lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
Resolution
&lt;/h5&gt;A number of methods may be employed to resolve this issue.  The most efficient and straightforward method, available in SQL 2005 and greater, is to use the &lt;a href="http://msdn.microsoft.com/en-us/library/ms186734.aspx" class="externalLink"&gt;ROW_NUMBER()&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt; function.  &lt;br /&gt; &lt;br /&gt;Using the &lt;a href="http://www.codeplex.com/MSFTDBProdSamples" class="externalLink"&gt;AdventureWorks&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt; database:&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
--Use ROW_NUMBER() to establish a LoginKey for each row
SELECT	LoginID, ROW_NUMBER() OVER (ORDER BY LoginID ASC) AS RowKey
FROM		HumanResources.EmployeeLogins
Once we have the ROW_NUMBER() query, we can use it in a Common Table Expression in order to update the RowKey in our HumanResources.EmployeeLogins table:
;WITH	RowKeys (LoginID, RowKey) AS 
		(SELECT	LoginID, 
				ROW_NUMBER() OVER (ORDER BY LoginID ASC) AS RowKey
		FROM	HumanResources.EmployeeLogins)
UPDATE	HumanResources.EmployeeLogins
SET		RowKey = rk.RowKey
FROM		HumanResources.EmployeeLogins el
JOIN		RowKeys rk ON el.LoginID = rk.LoginID
&lt;/pre&gt;ROW_NUMBER() can also be used to number rows based upon logical groupings, or partitions in data, although this is less applicable to cursor replacement.  For instance, the test data contains logins from multiple domains, and you may want to number the rows in the table based upon their position within a grouping of rows from the same domain.&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
--Use ROW_NUMBER in conjunction with PARTITION to create row numbers grouped by domain
SELECT	LoginID, 
		ROW_NUMBER() OVER 
			(PARTITION BY LEFT(LoginID, CHARINDEX('\', LoginID) - 1) 
			ORDER BY LoginID ASC) AS RowKey
FROM		HumanResources.EmployeeLogins
&lt;/pre&gt;Also worth noting is that the sort order of the OVER clause does not have to match the sort order of the outermost query. &lt;br /&gt;In the event that the numbering has to start at a number other than zero, that number can be added to ROW_NUMBER() in order to obtain the desired row numbers.  &lt;br /&gt;For instance:&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
SELECT	LoginID, 
		100 + ROW_NUMBER() OVER 
			(PARTITION BY LEFT(LoginID, CHARINDEX('\', LoginID) - 1) 
			ORDER BY LoginID ASC) AS RowKey
FROM		HumanResources.EmployeeLogins
&lt;/pre&gt;The same function can be performed, albeit far less efficiently, in SQL 2000.  The following solution uses an inline subquery in order to COUNT the number of rows on or before a given LoginID:&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
SELECT	el1.LoginID,
		(SELECT COUNT(LoginID)
		FROM	HumanResources.EmployeeLogins el2
		WHERE	el2.LoginID &amp;lt;= el1.LoginID) AS RowKey
FROM	HumanResources.EmployeeLogins el1
&lt;/pre&gt;This solution is subject to error if duplicate values are present in the columns being used for comparison.   If there were two identical LoginIDs, they would both be granted the same RowKey.   When dealing with duplicate fields such as this, a local temporary table can be used in order to ensure unique row numbering:&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
CREATE TABLE #EmployeeLoginsTemp
	(RowKey int IDENTITY(1,1) NOT NULL,
	LoginID nvarchar(256))
 
INSERT #EmployeeLoginsTemp (LoginID)
SELECT LoginID FROM HumanResources.EmployeeLogins
 
SELECT * FROM #EmployeeLoginsTemp
&lt;/pre&gt; &lt;br /&gt; &lt;br /&gt;&lt;a name="CustomIdentityFunctions"&gt;&lt;/a&gt;&lt;br /&gt;&lt;h5&gt;
Problem: Need to use a custom identity function to perform an insert
&lt;/h5&gt;Many databases employ custom identity generation functions.  There are VERY FEW good reasons for using custom identity functions in SQL Server, given the presence of &lt;a href="http://msdn.microsoft.com/en-us/library/aa933196(SQL.80).aspx" class="externalLink"&gt;IDENTITY&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt; columns and the &lt;a href="http://msdn.microsoft.com/en-us/library/ms187942.aspx" class="externalLink"&gt;UniqueIdentifier&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt; data type.  That is not to say that you will never encounter such a situation - just that all possible alternatives should be vetted prior to deciding upon a custom identity solution.&lt;br /&gt;A custom identity function commonly resembles the following:&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
CREATE TABLE Identities (TableName sysname PRIMARY KEY CLUSTERED,
						NextKey int NOT NULL)
 
CREATE PROC GetNextKey(	@TableName sysname,
						@NextKey int OUTPUT)
AS
BEGIN
	--Fetch the NextID, if there is a row for the passed-in TableName in the Identities.
	SELECT	@NextKey = NextKey
	FROM	Identities
	WHERE	TableName = @TableName
 
	--If there wasn't a row, @NextID will be NULL.
	IF @NextKey IS NULL
	BEGIN
		INSERT Identities (TableName, NextKey)
		SELECT @TableName, 1
 
		SELECT	@NextKey = NextKey
		FROM	Identities
		WHERE	TableName = @TableName
	END
 
	--Advance the NextID value in Identities
	UPDATE	Identities
	SET		NextKey = NextKey + 1
	WHERE	TableName = @TableName
END
&lt;/pre&gt; &lt;br /&gt;&lt;h5&gt;
Resolution
&lt;/h5&gt;The biggest problem with custom identity functions is that they serialize inserts.  While the following solution (for SQL 2000 and greater) does not use a cursor, it does use a WHILE loop to call the GetNextKey proc once for each row in HumanResources.EmployeeLogins:&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
WHILE EXISTS (SELECT 1 FROM HumanResources.EmployeeLogins WHERE RowKey IS NULL)
BEGIN
	DECLARE @NextKey int
	EXEC dbo.GetNextKey 'HumanResources.EmployeeLogins', @NextKey OUTPUT
 
	UPDATE	HumanResources.EmployeeLogins
	SET		RowKey = @NextKey
	WHERE	LoginID = (SELECT TOP 1 LoginID FROM HumanResources.EmployeeLogins WHERE RowKey IS NULL)
END
&lt;/pre&gt; &lt;br /&gt;&lt;a name="CompareAdjacentRows"&gt;&lt;/a&gt;&lt;br /&gt;&lt;h5&gt;
Problem: Need to compare a row to adjacent rows in a table
&lt;/h5&gt;A typical example of this type of problem is “I need to know by how much the latest price increase changed the price of each item”.  The programmer often resorts to a cursor because they cannot understand how to compare each row with the previous row for the same item, where the previous row’s price was not equal to the current row’s price.&lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
Resolution
&lt;/h5&gt;In this situation, an inline query can be very useful.  The following solution works for SQL 2000 and higher, and uses a different AdventureWorks table for illustration.  In AdventureWorks, the Production.ProductListPriceHistory table stores pricing history for each item.  The current row is identified by a NULL EndDate, so we must compare the current row to the most recent row for the same item.&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
SELECT	plph1.ProductID,  plph1.ListPrice - 
		COALESCE((SELECT		TOP 1 ListPrice
				FROM		Production.ProductListPriceHistory plph2
				WHERE		EndDate IS NOT NULL
				AND			plph2.ProductID = plph1.ProductID
				ORDER BY	EndDate DESC), 
				plph1.ListPrice) AS LastPriceChangeAmount
FROM	Production.ProductListPriceHistory plph1
WHERE	plph1.EndDate IS NULL
&lt;/pre&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt;&lt;h4&gt;
Conclusion
&lt;/h4&gt;This article has demonstrated a number of alternatives to the use of cursors in Transact-SQL.  Please feel free to post any comments, questions, or suggestions regarding this article below.  For further help avoiding SQL cursors, post a question in the &lt;a href="http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=85&amp;amp;SiteID=1" class="externalLink"&gt;MSDN Transact-SQL Forum&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;.  However, please read Arnie Rowland’s article on &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PrepareQuestion&amp;amp;referringTitle=AlternativesToSQLCursors"&gt;how to prepare your question to increase the possibility of eliciting a suitable solution&lt;/a&gt; prior to doing so.&lt;br /&gt; &lt;br /&gt;&lt;a href="#Top"&gt;Return to Top&lt;/a&gt;&lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt;&lt;i&gt;Page Created By: Aaron Alton, December 9, 2008&lt;/i&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>AaronAlton</author><pubDate>Tue, 09 Dec 2008 08:14:16 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: AlternativesToSQLCursors 20081209A</guid></item><item><title>UPDATED WIKI: Home</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Home&amp;version=109</link><description>&lt;div class="wikidoc"&gt;
&lt;h3&gt;
Common Solutions for T-SQL Problems
&lt;/h3&gt;&lt;h6&gt;
&lt;i&gt;Information presented in this WIKI represents the suggestions, ideas, and opinions of Volunteer &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ContributorBios&amp;amp;referringTitle=Home"&gt;Moderators and Answerers&lt;/a&gt; who support the Microsoft MSDN SQL Server Forums. (Unless specifically stated otherwise, nothing should be construed to represent the official positions or opinions of Microsoft and/or its Employees.)&lt;/i&gt;
&lt;/h6&gt; &lt;br /&gt;Please direct any additional Questions to the &lt;a href="http://forums.microsoft.com/Forums/default.aspx?ForumGroupID=19&amp;amp;SiteID=1" class="externalLink"&gt;MSDN SQL Server Related Forums&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;How can I &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PrepareQuestion&amp;amp;referringTitle=Home"&gt;Prepare My Question&lt;/a&gt; to Increase the Possibility of Getting a Good Solution?&lt;br /&gt;What are the &lt;a href="http://www.microsoft.com/communities/conduct/default.mspx" class="externalLink"&gt;Rules of Conduct&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt; expected on the Forums?&lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;&lt;i&gt;How To&lt;/i&gt; Examples of Selected T-SQL Programming Constructs&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt; &lt;br /&gt;&lt;b&gt;Data Related Queries&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AuditOrBypassTriggerExecution&amp;amp;referringTitle=Home"&gt;Audit or Bypass Trigger Execution&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AlternativesToSQLCursors&amp;amp;referringTitle=Home"&gt;Alternatives To SQL Server Cursors&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=CreateACommaDelimitedList&amp;amp;referringTitle=Home"&gt;Create a Comma Delimited List&lt;/a&gt; from a Column in a Table&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=NumbersTable&amp;amp;referringTitle=Home"&gt;Create and Use A Numbers Table&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ResultsByRange&amp;amp;referringTitle=Home"&gt;Control Return Results by Range&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PurgeAllTables&amp;amp;referringTitle=Home"&gt;Delete All Data From All User Tables In A Database&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=RecursiveCTE&amp;amp;referringTitle=Home"&gt;Exploring Recursive Common Table Expressions (CTE)&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DuplicateRows&amp;amp;referringTitle=Home"&gt;Find and/or Delete Duplicate Rows&lt;/a&gt; in a Table&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FindDataBetweenDates&amp;amp;referringTitle=Home"&gt;Find Rows of Data Between Two Dates&lt;/a&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FirstAvailableTimeslot&amp;amp;referringTitle=Home"&gt;Find First Available Timeslot&lt;/a&gt; for Scheduling &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FindMissingListItems&amp;amp;referringTitle=Home"&gt;Find the Missing Parts of a List &lt;/a&gt; of Requirements&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Implementation%20of%20DDL%20Trigger%20in%20SQL%20Server%202005&amp;amp;referringTitle=Home"&gt;Implementation of DDL Trigger in SQL Server 2005&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=IncrementAlphaNumericValues&amp;amp;referringTitle=Home"&gt;Increment an AlphaNumeric Value&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ISNULL_COALESCE&amp;amp;referringTitle=Home"&gt;Use ISNULL() and COALESCE()&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=GetAppLock&amp;amp;referringTitle=Home"&gt;Lock a Stored Procedure for Single Use Only&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=QueryBasedUponAbsenceOfData&amp;amp;referringTitle=Home"&gt;Query an Object Whose Result Set Depends Upon the Lack of Data In Another Object&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=StringArrayInput&amp;amp;referringTitle=Home"&gt;Pass and Handle a Delimited String&lt;/a&gt; similar to handling an Array() of Values&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PIVOTData&amp;amp;referringTitle=Home"&gt;PIVOT Data Using T-SQL&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=RankValuesInGroups&amp;amp;referringTitle=Home"&gt;Rank Values in Groups&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=NonDynamicSearch&amp;amp;referringTitle=Home"&gt;Search all or partial columns without Dynamic SQL&lt;/a&gt; while avoiding SQL Injection&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DynamicSearch&amp;amp;referringTitle=Home"&gt;Search all or partial columns with Dynamic SQL&lt;/a&gt; while avoiding SQL Injection&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SelectTopNbyGroup&amp;amp;referringTitle=Home"&gt;SELECT TOP n by Group&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=UNPIVOTData&amp;amp;referringTitle=Home"&gt;UNPIVOT Data Using T-SQL&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;Maintenance Queries&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ExpressBackups&amp;amp;referringTitle=Home"&gt;Automate Backups in SQL Express&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DetachUserDatabases&amp;amp;referringTitle=Home"&gt;Detach All User Databases&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LastBackUpDate&amp;amp;referringTitle=Home"&gt;Find Last BackUp Date Of All Databases On Your Server&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AgentLongRunning&amp;amp;referringTitle=Home"&gt;Find Long Running Agent Jobs&lt;/a&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LongRunningProcs&amp;amp;referringTitle=Home"&gt;Find the TOP n Longest Running Procedures&lt;/a&gt; (or Queries), Ordered by Total Impact on Server &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ExpressMaintenance&amp;amp;referringTitle=Home"&gt;Performing Common Maintenance Tasks in SQL Express&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=TransferLogins&amp;amp;referringTitle=Home"&gt;Transfer Logins to Another Server&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;Best Practices and Guidelines&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Best%20practices%20%2c%20Design%20and%20Development%20guidelines%20for%20Microsoft%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Best practices , Design and Development guidelines for Microsoft SQL Server&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;SQL Server Maintenance&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AutomatedDBA&amp;amp;referringTitle=Home"&gt;Automating Common DBA Tasks&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SQL2000CDOSysMail&amp;amp;referringTitle=Home"&gt;Configuring SQL Server 2000 Notification with CDOSys&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DatabaseMailConfig&amp;amp;referringTitle=Home"&gt;Configuring SQL Server 2005/2008 Database Mail&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Log%20file%20growth%20in%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Log file growth in SQL Server&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FileSpaceMon&amp;amp;referringTitle=Home"&gt;Monitor free space in the database files&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DiskSpaceMon&amp;amp;referringTitle=Home"&gt;Monitor free space on the server hard disks&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ErrorLogMon&amp;amp;referringTitle=Home"&gt;Monitor the SQL Server Error Log&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LongRunningJobMon&amp;amp;referringTitle=Home"&gt;Monitor long running SQL Agent Jobs&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FailedJobMon&amp;amp;referringTitle=Home"&gt;Monitor failed SQL Agent Jobs&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ServiceStatusMon&amp;amp;referringTitle=Home"&gt;Monitor Service Status&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SystemLogMon&amp;amp;referringTitle=Home"&gt;Monitor System Event Logs&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ProcessInfoMon&amp;amp;referringTitle=Home"&gt;Monitor Running Process Information&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Transfer%20Jobs%20and%20Logins%20using%20SSIS&amp;amp;referringTitle=Home"&gt;Transfer Jobs and Logins using SSIS&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Upgrading%20Steps%20to%20SQL%20Server%202005&amp;amp;referringTitle=Home"&gt;Upgrading Steps to SQL Server 2005&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;SQL Server 2008&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Manage%20unstructured%20data%20using%20FILESTREAM%20Feature%20in%20SQL%20Server%202008&amp;amp;referringTitle=Home"&gt;Manage unstructured data using FILESTREAM Feature in SQL Server 2008&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;&lt;i&gt;How To&lt;/i&gt; Troubleshoot and Debug T-SQL Code&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Troubleshoot%20Deadlocking%20in%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Troubleshoot Deadlocking in SQL Server&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Troubleshoot%20Deadlocking%20in%20SQL%20Server%202005%20using%20Profiler&amp;amp;referringTitle=Home"&gt;Troubleshoot Deadlocking in SQL Server 2005 using Profiler&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DeadlockAnatomy&amp;amp;referringTitle=Home"&gt;Understanding the Anatomy of a Deadlock&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Profiler&amp;amp;referringTitle=Home"&gt;Using the SQL Server Profiler&lt;/a&gt;.&lt;br /&gt; &lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;Writing Transact-SQL Statements Tutorial&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt;&lt;a href="http://msdn2.microsoft.com/en-us/library/ms365303.aspx" class="externalLink"&gt;http://msdn2.microsoft.com/en-us/library/ms365303.aspx&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt;&lt;i&gt;Page Created&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=WikiGuidelines&amp;amp;referringTitle=Home"&gt; &lt;/a&gt;By: Arnie Rowland, Mar 12, 2008&lt;/i&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>AaronAlton</author><pubDate>Tue, 09 Dec 2008 08:12:53 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: Home 20081209A</guid></item><item><title>UPDATED WIKI: AlternativesToSQLCursors</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AlternativesToSQLCursors&amp;version=2</link><description>&lt;div class="wikidoc"&gt;
&lt;h3&gt;
Alternatives To SQL Server Cursors
&lt;/h3&gt;&lt;h6&gt;
&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ContributorBios&amp;amp;referringTitle=AlternativesToSQLCursors&amp;amp;ANCHOR#AaronAlton"&gt;Aaron Alton&lt;/a&gt;, December 2008
&lt;/h6&gt; &lt;br /&gt;&lt;h4&gt;
Introduction
&lt;/h4&gt;Anyone with more than a little exposure to SQL Server will soon come to the conclusion that the use of cursors is best avoided.  SQL Server is a &lt;a href="http://en.wikipedia.org/wiki/RDBMS" class="externalLink"&gt;Relational Database Management System&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;, and as such is very proficient at processing sets of data.  The use of a cursor effectively repeats an operation once for each row being processed, thereby consuming far more server resources than would be necessitated by a set-based operation.  In addition, since SQL cursors are processed much more slowly than set-based operations, any locks generated by the use of said cursor are held longer than would otherwise be necessary.  In this way, the use of a cursor can affect not only the performance of a given batch of work, but also the performance of any other batches which need to make use of the same data resources.&lt;br /&gt; &lt;br /&gt;In order to effectively avoid using a SQL cursor, one must know why a cursor is being used in the first place.  The list below details the most common reasons why people use cursors, and some possible solutions for each problem.&lt;br /&gt; &lt;br /&gt;&lt;a href="#Test_Data"&gt;Test Data&lt;/a&gt;&lt;br /&gt;&lt;a href="#NewToSQL"&gt;Problem: The Developer or Designer is new to SQL Server&lt;/a&gt;&lt;br /&gt;&lt;a href="#UpdateWithRowKey"&gt;Problem: Need to update a table with incrementing column values for records already in the table&lt;/a&gt;&lt;br /&gt;&lt;a href="#CustomIdentityFunctions"&gt;Problem: Need to use a custom identity function to perform an insert&lt;/a&gt;&lt;br /&gt;&lt;a href="#CompareAdjacentRows"&gt;Problem: Need to compare a row to adjacent rows in a table&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;a name="NewToSQL"&gt;&lt;/a&gt;&lt;br /&gt;&lt;h5&gt;
Test Data:
&lt;/h5&gt;The following test data is used for each of the resolutions below.&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
USE AdventureWorks;
 
--Set up test data
IF (SELECT OBJECT_ID('HumanResources.EmployeeLogins')) IS NOT NULL
BEGIN
	DROP TABLE HumanResources.EmployeeLogins
END
 
CREATE TABLE HumanResources.EmployeeLogins 
	(RowKey		int NULL,
	LoginID		nvarchar(256) NOT NULL);
 
INSERT HumanResources.EmployeeLogins (LoginID)
SELECT LoginID FROM HumanResources.Employee
 
INSERT HumanResources.EmployeeLogins (LoginID)
SELECT 'Skunk-Works' + RIGHT(LoginID, LEN(LoginID) - CHARINDEX('\', LoginID) + 1)
FROM   HumanResources.Employee
&lt;/pre&gt;This test data is somewhat contrived, however it is an accessible example for anyone who has AdventureWorks installed.&lt;br /&gt; &lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
Problem: The Developer or Designer is New to SQL Server 
&lt;/h5&gt;By far, this is the most common reason for cursor usage.  If a programmer is already well versed in an event-driven programming language such as Visual Basic, they will possess a great wealth of experience in dealing with data items one at a time.  As such, their natural inclination when moving into SQL is to do the same.  Unfortunately, what is appropriate in one language may be (and in this case is) entirely inappropriate in another.  &lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
Resolution
&lt;/h5&gt;The primary weapon against cursor usage in this scenario is to develop a strong understanding of the basics of Transact-SQL.  There are countless courses, books, and websites dedicated to the topic.  In addition, you can review the examples below, which present set-based solutions to problems which may otherwise necessitate a cursor.&lt;br /&gt;If you’re still struggling with finding a set-based solution, post a question in the &lt;a href="http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=85&amp;amp;SiteID=1" class="externalLink"&gt;MSDN Transact-SQL Forum&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;.  Before doing so, review Arnie Rowland’s article on &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PrepareQuestion&amp;amp;referringTitle=AlternativesToSQLCursors"&gt;how to prepare your question to increase the possibility of eliciting a suitable solution&lt;/a&gt;.&lt;br /&gt; &lt;br /&gt; &lt;br /&gt;&lt;a name="UpdateWithRowKey"&gt;&lt;/a&gt;&lt;br /&gt;&lt;h5&gt;
Problem: Need to update a table with incrementing column values for records already in the table
&lt;/h5&gt;This problem is most often encountered when importing data from an external data source.  The external data source may not have a key field, for instance, and for one of various reasons, an identity column cannot be used while importing. &lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
Resolution
&lt;/h5&gt;A number of methods may be employed to resolve this issue.  The most efficient and straightforward method, available in SQL 2005 and greater, is to use the &lt;a href="http://msdn.microsoft.com/en-us/library/ms186734.aspx" class="externalLink"&gt;ROW_NUMBER()&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt; function.  &lt;br /&gt; &lt;br /&gt;Using the &lt;a href="http://www.codeplex.com/MSFTDBProdSamples" class="externalLink"&gt;AdventureWorks&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt; database:&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
--Use ROW_NUMBER() to establish a LoginKey for each row
SELECT	LoginID, ROW_NUMBER() OVER (ORDER BY LoginID ASC) AS RowKey
FROM		HumanResources.EmployeeLogins
Once we have the ROW_NUMBER() query, we can use it in a Common Table Expression in order to update the RowKey in our HumanResources.EmployeeLogins table:
;WITH	RowKeys (LoginID, RowKey) AS 
		(SELECT	LoginID, 
				ROW_NUMBER() OVER (ORDER BY LoginID ASC) AS RowKey
		FROM	HumanResources.EmployeeLogins)
UPDATE	HumanResources.EmployeeLogins
SET		RowKey = rk.RowKey
FROM		HumanResources.EmployeeLogins el
JOIN		RowKeys rk ON el.LoginID = rk.LoginID
&lt;/pre&gt;ROW_NUMBER() can also be used to number rows based upon logical groupings, or partitions in data, although this is less applicable to cursor replacement.  For instance, the test data contains logins from multiple domains, and you may want to number the rows in the table based upon their position within a grouping of rows from the same domain.&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
--Use ROW_NUMBER in conjunction with PARTITION to create row numbers grouped by domain
SELECT	LoginID, 
		ROW_NUMBER() OVER 
			(PARTITION BY LEFT(LoginID, CHARINDEX('\', LoginID) - 1) 
			ORDER BY LoginID ASC) AS RowKey
FROM		HumanResources.EmployeeLogins
&lt;/pre&gt;Also worth noting is that the sort order of the OVER clause does not have to match the sort order of the outermost query. &lt;br /&gt;In the event that the numbering has to start at a number other than zero, that number can be added to ROW_NUMBER() in order to obtain the desired row numbers.  &lt;br /&gt;For instance:&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
SELECT	LoginID, 
		100 + ROW_NUMBER() OVER 
			(PARTITION BY LEFT(LoginID, CHARINDEX('\', LoginID) - 1) 
			ORDER BY LoginID ASC) AS RowKey
FROM		HumanResources.EmployeeLogins
&lt;/pre&gt;The same function can be performed, albeit far less efficiently, in SQL 2000.  The following solution uses an inline subquery in order to COUNT the number of rows on or before a given LoginID:&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
SELECT	el1.LoginID,
		(SELECT COUNT(LoginID)
		FROM	HumanResources.EmployeeLogins el2
		WHERE	el2.LoginID &amp;lt;= el1.LoginID) AS RowKey
FROM	HumanResources.EmployeeLogins el1
&lt;/pre&gt;This solution is subject to error if duplicate values are present in the columns being used for comparison.   If there were two identical LoginIDs, they would both be granted the same RowKey.   When dealing with duplicate fields such as this, a local temporary table can be used in order to ensure unique row numbering:&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
CREATE TABLE #EmployeeLoginsTemp
	(RowKey int IDENTITY(1,1) NOT NULL,
	LoginID nvarchar(256))
 
INSERT #EmployeeLoginsTemp (LoginID)
SELECT LoginID FROM HumanResources.EmployeeLogins
 
SELECT * FROM #EmployeeLoginsTemp
&lt;/pre&gt; &lt;br /&gt; &lt;br /&gt;&lt;a name="CustomIdentityFunctions"&gt;&lt;/a&gt;&lt;br /&gt;&lt;h5&gt;
Problem: Need to use a custom identity function to perform an insert
&lt;/h5&gt;Many databases employ custom identity generation functions.  There are VERY FEW good reasons for using custom identity functions in SQL Server, given the presence of &lt;a href="http://msdn.microsoft.com/en-us/library/aa933196(SQL.80).aspx" class="externalLink"&gt;IDENTITY&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt; columns and the &lt;a href="http://msdn.microsoft.com/en-us/library/ms187942.aspx" class="externalLink"&gt;UniqueIdentifier&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt; data type.  That is not to say that you will never encounter such a situation - just that all possible alternatives should be vetted prior to deciding upon a custom identity solution.&lt;br /&gt;A custom identity function commonly resembles the following:&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
CREATE TABLE Identities (TableName sysname PRIMARY KEY CLUSTERED,
						NextKey int NOT NULL)
 
CREATE PROC GetNextKey(	@TableName sysname,
						@NextKey int OUTPUT)
AS
BEGIN
	--Fetch the NextID, if there is a row for the passed-in TableName in the Identities.
	SELECT	@NextKey = NextKey
	FROM	Identities
	WHERE	TableName = @TableName
 
	--If there wasn't a row, @NextID will be NULL.
	IF @NextKey IS NULL
	BEGIN
		INSERT Identities (TableName, NextKey)
		SELECT @TableName, 1
 
		SELECT	@NextKey = NextKey
		FROM	Identities
		WHERE	TableName = @TableName
	END
 
	--Advance the NextID value in Identities
	UPDATE	Identities
	SET		NextKey = NextKey + 1
	WHERE	TableName = @TableName
END
&lt;/pre&gt; &lt;br /&gt;&lt;h5&gt;
Resolution
&lt;/h5&gt;The biggest problem with custom identity functions is that they serialize inserts.  While the following solution (for SQL 2000 and greater) does not use a cursor, it does use a WHILE loop to call the GetNextKey proc once for each row in HumanResources.EmployeeLogins:&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
WHILE EXISTS (SELECT 1 FROM HumanResources.EmployeeLogins WHERE RowKey IS NULL)
BEGIN
	DECLARE @NextKey int
	EXEC dbo.GetNextKey 'HumanResources.EmployeeLogins', @NextKey OUTPUT
 
	UPDATE	HumanResources.EmployeeLogins
	SET		RowKey = @NextKey
	WHERE	LoginID = (SELECT TOP 1 LoginID FROM HumanResources.EmployeeLogins WHERE RowKey IS NULL)
END
&lt;/pre&gt; &lt;br /&gt;&lt;a name="CompareAdjacentRows"&gt;&lt;/a&gt;&lt;br /&gt;&lt;h5&gt;
Problem: Need to compare a row to adjacent rows in a table
&lt;/h5&gt;A typical example of this type of problem is “I need to know by how much the latest price increase changed the price of each item”.  The programmer often resorts to a cursor because they cannot understand how to compare each row with the previous row for the same item, where the previous row’s price was not equal to the current row’s price.&lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
Resolution
&lt;/h5&gt;In this situation, an inline query can be very useful.  The following solution works for SQL 2000 and higher, and uses a different AdventureWorks table for illustration.  In AdventureWorks, the Production.ProductListPriceHistory table stores pricing history for each item.  The current row is identified by a NULL EndDate, so we must compare the current row to the most recent row for the same item.&lt;br /&gt; &lt;br /&gt;&lt;pre&gt;
SELECT	plph1.ProductID,  plph1.ListPrice - 
		COALESCE((SELECT		TOP 1 ListPrice
				FROM		Production.ProductListPriceHistory plph2
				WHERE		EndDate IS NOT NULL
				AND			plph2.ProductID = plph1.ProductID
				ORDER BY	EndDate DESC), 
				plph1.ListPrice) AS LastPriceChangeAmount
FROM	Production.ProductListPriceHistory plph1
WHERE	plph1.EndDate IS NULL
&lt;/pre&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt;&lt;h4&gt;
Conclusion
&lt;/h4&gt;This article has demonstrated a number of alternatives to the use of cursors in Transact-SQL.  Please feel free to post any comments, questions, or suggestions regarding this article below.  For further help avoiding SQL cursors, post a question in the &lt;a href="http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=85&amp;amp;SiteID=1" class="externalLink"&gt;MSDN Transact-SQL Forum&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;.  However, please read Arnie Rowland’s article on &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PrepareQuestion&amp;amp;referringTitle=AlternativesToSQLCursors"&gt;how to prepare your question to increase the possibility of eliciting a suitable solution&lt;/a&gt; prior to doing so.&lt;br /&gt;
&lt;/div&gt;</description><author>AaronAlton</author><pubDate>Tue, 09 Dec 2008 08:11:56 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: AlternativesToSQLCursors 20081209A</guid></item><item><title>UPDATED WIKI: AlternativesToSQLCursors</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AlternativesToSQLCursors&amp;version=1</link><description>&lt;div class="wikidoc"&gt;
Alternatives To SQL Server Cursors&lt;br /&gt;Anyone with more than a little exposure to SQL Server will soon come to the conclusion that the use of cursors is best avoided.  SQL Server is a Relational Database Management System, and as such is very proficient at processing sets of data.  The use of a cursor effectively repeats an operation once for each row being processed, thereby consuming far more server resources than would be necessitated by a set-based operation.  In addition, since SQL cursors are processed much more slowly than set-based operations, any locks generated by the use of said cursor are held longer than would otherwise be necessary.  In this way, the use of a cursor can affect not only the performance of a given batch of work, but also the performance of any other batches which need to make use of the same data resources.&lt;br /&gt; &lt;br /&gt;In order to effectively avoid using a SQL cursor, one must first know why a cursor is being used in the first place.  The list below details the most common reasons why people use cursors, and some possible solutions for each problem.&lt;br /&gt; &lt;br /&gt;Test Data:&lt;br /&gt;The following test data is used for each of the resolutions below.&lt;br /&gt;USE AdventureWorks;&lt;br /&gt; &lt;br /&gt;--Set up test data&lt;br /&gt;IF (SELECT OBJECT_ID('HumanResources.EmployeeLogins')) IS NOT NULL&lt;br /&gt;BEGIN&lt;br /&gt;	DROP TABLE HumanResources.EmployeeLogins&lt;br /&gt;END&lt;br /&gt; &lt;br /&gt;CREATE TABLE HumanResources.EmployeeLogins &lt;br /&gt;	(RowKey		int NULL,&lt;br /&gt;	LoginID		nvarchar(256) NOT NULL);&lt;br /&gt; &lt;br /&gt;INSERT HumanResources.EmployeeLogins (LoginID)&lt;br /&gt;SELECT LoginID FROM HumanResources.Employee&lt;br /&gt; &lt;br /&gt;INSERT HumanResources.EmployeeLogins (LoginID)&lt;br /&gt;SELECT 'Skunk-Works' + RIGHT(LoginID, LEN(LoginID) - CHARINDEX('\', LoginID) + 1)&lt;br /&gt;FROM   HumanResources.Employee&lt;br /&gt;This test data is somewhat contrived, however it is an accessible example for anyone who has AdventureWorks installed.&lt;br /&gt; &lt;br /&gt; &lt;br /&gt;Problem: The Developer or Designer is New to SQL Server &lt;br /&gt;By far, this is the most common reason for cursor usage.  If a programmer is already well versed in an event-driven programming language such as Visual Basic, they will possess a great wealth of experience in dealing with data items one at a time.  As such, their natural inclination when moving into SQL is to do the same.  Unfortunately, what is appropriate in one language may be (and in this case is) entirely inappropriate in another.  &lt;br /&gt;Resolution:&lt;br /&gt;The primary weapon against cursor usage in this scenario is to develop a strong understanding of the basics of Transact-SQL.  There are countless courses, books, and websites dedicated to the topic.  In addition, you can review the examples below, which present set-based solutions to problems which may otherwise necessitate a cursor.&lt;br /&gt;If you’re still struggling with finding a set-based solution, post a question in the MSDN Transact-SQL Forum.  Before doing so, review Arnie Rowland’s article on how to prepare your question to increase the possibility of eliciting a suitable solution.&lt;br /&gt; &lt;br /&gt;Problem: Need to update a table with incrementing column values for records already in the table&lt;br /&gt;Resolution: This problem is most often encountered when importing data from an external data source.  The external data source may not have a key field, for instance, and for one of various reasons, an identity column cannot be used while importing. &lt;br /&gt;A number of methods may be employed to resolve this issue, however the most efficient and straightforward method, available in SQL 2005 and greater, is to use the ROW_NUMBER() function.  Using the AdventureWorks database:&lt;br /&gt;--Use ROW_NUMBER() to establish a LoginKey for each row&lt;br /&gt;SELECT	LoginID, ROW_NUMBER() OVER (ORDER BY LoginID ASC) AS RowKey&lt;br /&gt;FROM		HumanResources.EmployeeLogins&lt;br /&gt;Once we have the ROW_NUMBER() query, we can use it in a Common Table Expression in order to update the RowKey in our HumanResources.EmployeeLogins table:&lt;br /&gt;;WITH	RowKeys (LoginID, RowKey) AS &lt;br /&gt;		(SELECT	LoginID, &lt;br /&gt;				ROW_NUMBER() OVER (ORDER BY LoginID ASC) AS RowKey&lt;br /&gt;		FROM	HumanResources.EmployeeLogins)&lt;br /&gt;UPDATE	HumanResources.EmployeeLogins&lt;br /&gt;SET		RowKey = rk.RowKey&lt;br /&gt;FROM		HumanResources.EmployeeLogins el&lt;br /&gt;JOIN		RowKeys rk ON el.LoginID = rk.LoginID&lt;br /&gt;ROW_NUMBER() can also be used to number rows based upon logical groupings, or partitions in data, although this is less applicable to cursor replacement.  For instance, the test data contains logins from multiple domains, and you may want to number the rows in the table based upon their position within a grouping of rows from the same domain.&lt;br /&gt;--Use ROW_NUMBER in conjunction with PARTITION to create row numbers grouped by domain&lt;br /&gt;SELECT	LoginID, &lt;br /&gt;		ROW_NUMBER() OVER &lt;br /&gt;			(PARTITION BY LEFT(LoginID, CHARINDEX('\', LoginID) - 1) &lt;br /&gt;			ORDER BY LoginID ASC) AS RowKey&lt;br /&gt;FROM		HumanResources.EmployeeLogins&lt;br /&gt;Also worth noting is that the sort order of the OVER clause does not have to match the sort order of the outermost query. &lt;br /&gt;In the event that the numbering has to start at a number other than zero, that number can be added to ROW_NUMBER() in order to obtain the desired row numbers.  For instance:&lt;br /&gt;SELECT	LoginID, &lt;br /&gt;		100 + ROW_NUMBER() OVER &lt;br /&gt;			(PARTITION BY LEFT(LoginID, CHARINDEX('\', LoginID) - 1) &lt;br /&gt;			ORDER BY LoginID ASC) AS RowKey&lt;br /&gt;FROM		HumanResources.EmployeeLogins&lt;br /&gt;The same function can be performed, albeit far less efficiently, in SQL 2000.  The following solution uses an inline subquery in order to COUNT the number of rows on or before a given LoginID:&lt;br /&gt;SELECT	el1.LoginID,&lt;br /&gt;		(SELECT COUNT(LoginID)&lt;br /&gt;		FROM	HumanResources.EmployeeLogins el2&lt;br /&gt;		WHERE	el2.LoginID &amp;lt;= el1.LoginID) AS RowKey&lt;br /&gt;FROM	HumanResources.EmployeeLogins el1&lt;br /&gt;This solution is subject to error if duplicate values are present in the columns being used for comparison.   If there were two identical LoginIDs, they would both be granted the same RowKey.   When dealing with duplicate fields such as this, a local temporary table can be used in order to ensure unique row numbering:&lt;br /&gt;CREATE TABLE #EmployeeLoginsTemp&lt;br /&gt;	(RowKey int IDENTITY(1,1) NOT NULL,&lt;br /&gt;	LoginID nvarchar(256))&lt;br /&gt; &lt;br /&gt;INSERT #EmployeeLoginsTemp (LoginID)&lt;br /&gt;SELECT LoginID FROM HumanResources.EmployeeLogins&lt;br /&gt; &lt;br /&gt;SELECT * FROM #EmployeeLoginsTemp&lt;br /&gt; &lt;br /&gt; &lt;br /&gt;Problem: Need to use a custom identity function to perform an insert&lt;br /&gt;Resolution: Many databases employee custom identity generation functions.  There are VERY FEW good reasons for using custom identity functions in SQL Server, given the presence of IDENTITY columns and the UniqueIdentifier data type.  That is not to say that you will never encounter such a situation - just that all possible alternatives should be vetted prior to deciding upon a custom identity solution.&lt;br /&gt;A custom identity function commonly resembles the following:&lt;br /&gt;CREATE TABLE Identities (TableName sysname PRIMARY KEY CLUSTERED,&lt;br /&gt;						NextKey int NOT NULL)&lt;br /&gt; &lt;br /&gt;CREATE PROC GetNextKey(	@TableName sysname,&lt;br /&gt;						@NextKey int OUTPUT)&lt;br /&gt;AS&lt;br /&gt;BEGIN&lt;br /&gt;	--Fetch the NextID, if there is a row for the passed-in TableName in the Identities.&lt;br /&gt;	SELECT	@NextKey = NextKey&lt;br /&gt;	FROM	Identities&lt;br /&gt;	WHERE	TableName = @TableName&lt;br /&gt; &lt;br /&gt;	--If there wasn't a row, @NextID will be NULL.&lt;br /&gt;	IF @NextKey IS NULL&lt;br /&gt;	BEGIN&lt;br /&gt;		INSERT Identities (TableName, NextKey)&lt;br /&gt;		SELECT @TableName, 1&lt;br /&gt; &lt;br /&gt;		SELECT	@NextKey = NextKey&lt;br /&gt;		FROM	Identities&lt;br /&gt;		WHERE	TableName = @TableName&lt;br /&gt;	END&lt;br /&gt; &lt;br /&gt;	--Advance the NextID value in Identities&lt;br /&gt;	UPDATE	Identities&lt;br /&gt;	SET		NextKey = NextKey + 1&lt;br /&gt;	WHERE	TableName = @TableName&lt;br /&gt;END&lt;br /&gt;The biggest problem with custom identity functions is that they serialize inserts.  While the following solution (for SQL 2000 and greater) does not use a cursor, it does use a WHILE loop to call the GetNextKey proc once for each row in HumanResources.EmployeeLogins:&lt;br /&gt;WHILE EXISTS (SELECT 1 FROM HumanResources.EmployeeLogins WHERE RowKey IS NULL)&lt;br /&gt;BEGIN&lt;br /&gt;	DECLARE @NextKey int&lt;br /&gt;	EXEC dbo.GetNextKey 'HumanResources.EmployeeLogins', @NextKey OUTPUT&lt;br /&gt; &lt;br /&gt;	UPDATE	HumanResources.EmployeeLogins&lt;br /&gt;	SET		RowKey = @NextKey&lt;br /&gt;	WHERE	LoginID = (SELECT TOP 1 LoginID FROM HumanResources.EmployeeLogins WHERE RowKey IS NULL)&lt;br /&gt;END&lt;br /&gt; &lt;br /&gt;Problem: Need to compare a row to adjacent rows in a table&lt;br /&gt;A typical example of this type of problem is “I need to know by how much the latest price increase changed the price of each item”.  The programmer often resorts to a cursor because they cannot understand how to compare each row with the previous row for the same item, where the previous row’s price was not equal to the current row’s price.&lt;br /&gt;In this situation, an inline query can be very useful.  The following solution works for SQL 2000 and higher, and uses a different AdventureWorks table for illustration.  In AdventureWorks, the Production.ProductListPriceHistory table stores pricing history for each item.  The current row is identified by a NULL EndDate, so we must compare the current row to the most recent row for the same item.&lt;br /&gt;SELECT	plph1.ProductID,  plph1.ListPrice - &lt;br /&gt;		COALESCE((SELECT		TOP 1 ListPrice&lt;br /&gt;				FROM		Production.ProductListPriceHistory plph2&lt;br /&gt;				WHERE		EndDate IS NOT NULL&lt;br /&gt;				AND			plph2.ProductID = plph1.ProductID&lt;br /&gt;				ORDER BY	EndDate DESC), &lt;br /&gt;				plph1.ListPrice) AS LastPriceChangeAmount&lt;br /&gt;FROM	Production.ProductListPriceHistory plph1&lt;br /&gt;WHERE	plph1.EndDate IS NULL&lt;br /&gt; &lt;br /&gt; Conclusion&lt;br /&gt;This article has demonstrated a number of alternatives to the use of cursors in Transact-SQL.  Please feel free to post any comments, questions, or suggestions regarding this article below.  For help avoiding SQL cursors, please read Arnie Rowland’s article on how to prepare your question to increase the possibility of eliciting a suitable solution, and then post a question in the MSDN T-SQL Forums.&lt;br /&gt;
&lt;/div&gt;</description><author>AaronAlton</author><pubDate>Tue, 09 Dec 2008 01:00:30 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: AlternativesToSQLCursors 20081209A</guid></item><item><title>UPDATED WIKI: TestPage</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=TestPage&amp;version=70</link><description>&lt;div class="wikidoc"&gt;
&lt;h5&gt;
Test Environment
&lt;/h5&gt;You may create links here to your new Wiki page in order to work on it and keep it out of Public view until you are ready to make it 'public'. &lt;br /&gt;     Then when you are ready to make your page 'Public', note the Wiki PageName, and use it for the Wiki link on the referring page. &lt;br /&gt;     After your page is complete, and you have 'published' it, you may wish to remove the link from this page.&lt;br /&gt; &lt;br /&gt;     &lt;b&gt;WikiLink:  [Words Seen by User|YourWikiPage]&lt;/b&gt;&lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Transfer%20Jobs%20and%20Logins%20using%20SSIS&amp;amp;referringTitle=TestPage"&gt;Transfer Jobs and Logins using SSIS&lt;/a&gt; - Deepak&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Upgrading%20to%20SQL%20Server%202005&amp;amp;referringTitle=TestPage"&gt;Upgrading to SQL Server 2005&lt;/a&gt; - Deepak&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Log%20file%20growth%20in%20SQL%20Server&amp;amp;referringTitle=TestPage"&gt;Log file growth in SQL Server&lt;/a&gt; - Deepak&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AlternativesToSQLCursors&amp;amp;referringTitle=TestPage"&gt;Alternatives to SQL Cursors&lt;/a&gt; - Aaron&lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DetachDatabaseVideo&amp;amp;referringTitle=TestPage"&gt;Detaching A Database with SSMS&lt;/a&gt; - Video Tutorial&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ListPrimaryForeignKeyInTable&amp;amp;referringTitle=TestPage"&gt;Find out all the primary key and foreign key constraints in a table&lt;/a&gt; - Suprotim Agarwal&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=analytics&amp;amp;referringTitle=TestPage"&gt;Testing out analytics&lt;/a&gt; - Suprotim&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SQL%20Server%20Best%20Practices%20-%20Development&amp;amp;referringTitle=TestPage"&gt;SQL Server Best Practices - Development&lt;/a&gt; - Madhu&lt;br /&gt; &lt;br /&gt;This concept 'could' work -requires a counter.cgi hosted somewhere...&lt;br /&gt;(A bit tacky perhaps...)&lt;br /&gt;&lt;div class="video" style="text-align:center"&gt;
&lt;span class="player"&gt;&lt;object type="application/x-shockwave-flash" height="285" width="320" classid="CLSID:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"&gt;
&lt;param name="movie" value="http://www.indiana.edu/~counter/Count.cgi?df=MSDNMod-Page1.dat"&gt;

&lt;/param&gt;&lt;embed type="application/x-shockwave-flash" height="285" width="320" src="http://www.indiana.edu/~counter/Count.cgi?df=MSDNMod-Page1.dat" pluginspage="http://macromedia.com/go/getflashplayer" autoplay="false" autostart="false" /&gt;
&lt;/object&gt;&lt;/span&gt;&lt;br /&gt;&lt;span class="external"&gt;&lt;a href="http://www.indiana.edu/~counter/Count.cgi?df=MSDNMod-Page1.dat" target="_blank"&gt;Launch in another window&lt;/a&gt;&lt;/span&gt;
&lt;/div&gt;&lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ContributorBios&amp;amp;referringTitle=TestPage"&gt;Contributors&lt;/a&gt;&lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt;&lt;i&gt;Page Created By: Arnie Rowland, Mar 16, 2008&lt;/i&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>AaronAlton</author><pubDate>Tue, 09 Dec 2008 00:55:25 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: TestPage 20081209A</guid></item><item><title>UPDATED WIKI: Home</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Home&amp;version=108</link><description>&lt;div class="wikidoc"&gt;
&lt;h3&gt;
Common Solutions for T-SQL Problems
&lt;/h3&gt;&lt;h6&gt;
&lt;i&gt;Information presented in this WIKI represents the suggestions, ideas, and opinions of Volunteer &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ContributorBios&amp;amp;referringTitle=Home"&gt;Moderators and Answerers&lt;/a&gt; who support the Microsoft MSDN SQL Server Forums. (Unless specifically stated otherwise, nothing should be construed to represent the official positions or opinions of Microsoft and/or its Employees.)&lt;/i&gt;
&lt;/h6&gt; &lt;br /&gt;Please direct any additional Questions to the &lt;a href="http://forums.microsoft.com/Forums/default.aspx?ForumGroupID=19&amp;amp;SiteID=1" class="externalLink"&gt;MSDN SQL Server Related Forums&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;How can I &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PrepareQuestion&amp;amp;referringTitle=Home"&gt;Prepare My Question&lt;/a&gt; to Increase the Possibility of Getting a Good Solution?&lt;br /&gt;What are the &lt;a href="http://www.microsoft.com/communities/conduct/default.mspx" class="externalLink"&gt;Rules of Conduct&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt; expected on the Forums?&lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;&lt;i&gt;How To&lt;/i&gt; Examples of Selected T-SQL Programming Constructs&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt; &lt;br /&gt;&lt;b&gt;Data Related Queries&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AuditOrBypassTriggerExecution&amp;amp;referringTitle=Home"&gt;Audit or Bypass Trigger Execution&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=CreateACommaDelimitedList&amp;amp;referringTitle=Home"&gt;Create a Comma Delimited List&lt;/a&gt; from a Column in a Table&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=NumbersTable&amp;amp;referringTitle=Home"&gt;Create and Use A Numbers Table&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ResultsByRange&amp;amp;referringTitle=Home"&gt;Control Return Results by Range&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PurgeAllTables&amp;amp;referringTitle=Home"&gt;Delete All Data From All User Tables In A Database&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=RecursiveCTE&amp;amp;referringTitle=Home"&gt;Exploring Recursive Common Table Expressions (CTE)&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DuplicateRows&amp;amp;referringTitle=Home"&gt;Find and/or Delete Duplicate Rows&lt;/a&gt; in a Table&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FindDataBetweenDates&amp;amp;referringTitle=Home"&gt;Find Rows of Data Between Two Dates&lt;/a&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FirstAvailableTimeslot&amp;amp;referringTitle=Home"&gt;Find First Available Timeslot&lt;/a&gt; for Scheduling &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FindMissingListItems&amp;amp;referringTitle=Home"&gt;Find the Missing Parts of a List &lt;/a&gt; of Requirements&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Implementation%20of%20DDL%20Trigger%20in%20SQL%20Server%202005&amp;amp;referringTitle=Home"&gt;Implementation of DDL Trigger in SQL Server 2005&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=IncrementAlphaNumericValues&amp;amp;referringTitle=Home"&gt;Increment an AlphaNumeric Value&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ISNULL_COALESCE&amp;amp;referringTitle=Home"&gt;Use ISNULL() and COALESCE()&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=GetAppLock&amp;amp;referringTitle=Home"&gt;Lock a Stored Procedure for Single Use Only&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=QueryBasedUponAbsenceOfData&amp;amp;referringTitle=Home"&gt;Query an Object Whose Result Set Depends Upon the Lack of Data In Another Object&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=StringArrayInput&amp;amp;referringTitle=Home"&gt;Pass and Handle a Delimited String&lt;/a&gt; similar to handling an Array() of Values&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PIVOTData&amp;amp;referringTitle=Home"&gt;PIVOT Data Using T-SQL&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=RankValuesInGroups&amp;amp;referringTitle=Home"&gt;Rank Values in Groups&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=NonDynamicSearch&amp;amp;referringTitle=Home"&gt;Search all or partial columns without Dynamic SQL&lt;/a&gt; while avoiding SQL Injection&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DynamicSearch&amp;amp;referringTitle=Home"&gt;Search all or partial columns with Dynamic SQL&lt;/a&gt; while avoiding SQL Injection&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SelectTopNbyGroup&amp;amp;referringTitle=Home"&gt;SELECT TOP n by Group&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=UNPIVOTData&amp;amp;referringTitle=Home"&gt;UNPIVOT Data Using T-SQL&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;Maintenance Queries&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ExpressBackups&amp;amp;referringTitle=Home"&gt;Automate Backups in SQL Express&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DetachUserDatabases&amp;amp;referringTitle=Home"&gt;Detach All User Databases&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LastBackUpDate&amp;amp;referringTitle=Home"&gt;Find Last BackUp Date Of All Databases On Your Server&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AgentLongRunning&amp;amp;referringTitle=Home"&gt;Find Long Running Agent Jobs&lt;/a&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LongRunningProcs&amp;amp;referringTitle=Home"&gt;Find the TOP n Longest Running Procedures&lt;/a&gt; (or Queries), Ordered by Total Impact on Server &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ExpressMaintenance&amp;amp;referringTitle=Home"&gt;Performing Common Maintenance Tasks in SQL Express&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=TransferLogins&amp;amp;referringTitle=Home"&gt;Transfer Logins to Another Server&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;Best Practices and Guidelines&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Best%20practices%20%2c%20Design%20and%20Development%20guidelines%20for%20Microsoft%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Best practices , Design and Development guidelines for Microsoft SQL Server&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;SQL Server Maintenance&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AutomatedDBA&amp;amp;referringTitle=Home"&gt;Automating Common DBA Tasks&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SQL2000CDOSysMail&amp;amp;referringTitle=Home"&gt;Configuring SQL Server 2000 Notification with CDOSys&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DatabaseMailConfig&amp;amp;referringTitle=Home"&gt;Configuring SQL Server 2005/2008 Database Mail&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Log%20file%20growth%20in%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Log file growth in SQL Server&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FileSpaceMon&amp;amp;referringTitle=Home"&gt;Monitor free space in the database files&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DiskSpaceMon&amp;amp;referringTitle=Home"&gt;Monitor free space on the server hard disks&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ErrorLogMon&amp;amp;referringTitle=Home"&gt;Monitor the SQL Server Error Log&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LongRunningJobMon&amp;amp;referringTitle=Home"&gt;Monitor long running SQL Agent Jobs&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FailedJobMon&amp;amp;referringTitle=Home"&gt;Monitor failed SQL Agent Jobs&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ServiceStatusMon&amp;amp;referringTitle=Home"&gt;Monitor Service Status&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SystemLogMon&amp;amp;referringTitle=Home"&gt;Monitor System Event Logs&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ProcessInfoMon&amp;amp;referringTitle=Home"&gt;Monitor Running Process Information&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Transfer%20Jobs%20and%20Logins%20using%20SSIS&amp;amp;referringTitle=Home"&gt;Transfer Jobs and Logins using SSIS&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Upgrading%20Steps%20to%20SQL%20Server%202005&amp;amp;referringTitle=Home"&gt;Upgrading Steps to SQL Server 2005&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;SQL Server 2008&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Manage%20unstructured%20data%20using%20FILESTREAM%20Feature%20in%20SQL%20Server%202008&amp;amp;referringTitle=Home"&gt;Manage unstructured data using FILESTREAM Feature in SQL Server 2008&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;&lt;i&gt;How To&lt;/i&gt; Troubleshoot and Debug T-SQL Code&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Troubleshoot%20Deadlocking%20in%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Troubleshoot Deadlocking in SQL Server&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Troubleshoot%20Deadlocking%20in%20SQL%20Server%202005%20using%20Profiler&amp;amp;referringTitle=Home"&gt;Troubleshoot Deadlocking in SQL Server 2005 using Profiler&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DeadlockAnatomy&amp;amp;referringTitle=Home"&gt;Understanding the Anatomy of a Deadlock&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Profiler&amp;amp;referringTitle=Home"&gt;Using the SQL Server Profiler&lt;/a&gt;.&lt;br /&gt; &lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;Writing Transact-SQL Statements Tutorial&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt;&lt;a href="http://msdn2.microsoft.com/en-us/library/ms365303.aspx" class="externalLink"&gt;http://msdn2.microsoft.com/en-us/library/ms365303.aspx&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt;&lt;i&gt;Page Created&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=WikiGuidelines&amp;amp;referringTitle=Home"&gt; &lt;/a&gt;By: Arnie Rowland, Mar 12, 2008&lt;/i&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>JonathanKehayias</author><pubDate>Mon, 01 Dec 2008 21:56:06 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: Home 20081201P</guid></item><item><title>UPDATED WIKI: Home</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Home&amp;version=107</link><description>&lt;div class="wikidoc"&gt;
&lt;h3&gt;
Common Solutions for T-SQL Problems
&lt;/h3&gt;&lt;h6&gt;
&lt;i&gt;Information presented in this WIKI represents the suggestions, ideas, and opinions of Volunteer &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ContributorBios&amp;amp;referringTitle=Home"&gt;Moderators and Answerers&lt;/a&gt; who support the Microsoft MSDN SQL Server Forums. (Unless specifically stated otherwise, nothing should be construed to represent the official positions or opinions of Microsoft and/or its Employees.)&lt;/i&gt;
&lt;/h6&gt; &lt;br /&gt;Please direct any additional Questions to the &lt;a href="http://forums.microsoft.com/Forums/default.aspx?ForumGroupID=19&amp;amp;SiteID=1" class="externalLink"&gt;MSDN SQL Server Related Forums&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;How can I &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PrepareQuestion&amp;amp;referringTitle=Home"&gt;Prepare My Question&lt;/a&gt; to Increase the Possibility of Getting a Good Solution?&lt;br /&gt;What are the &lt;a href="http://www.microsoft.com/communities/conduct/default.mspx" class="externalLink"&gt;Rules of Conduct&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt; expected on the Forums?&lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;&lt;i&gt;How To&lt;/i&gt; Examples of Selected T-SQL Programming Constructs&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt; &lt;br /&gt;&lt;b&gt;Data Related Queries&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AuditOrBypassTriggerExecution&amp;amp;referringTitle=Home"&gt;Audit or Bypass Trigger Execution&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=CreateACommaDelimitedList&amp;amp;referringTitle=Home"&gt;Create a Comma Delimited List&lt;/a&gt; from a Column in a Table&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=NumbersTable&amp;amp;referringTitle=Home"&gt;Create and Use A Numbers Table&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ResultsByRange&amp;amp;referringTitle=Home"&gt;Control Return Results by Range&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PurgeAllTables&amp;amp;referringTitle=Home"&gt;Delete All Data From All User Tables In A Database&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=RecursiveCTE&amp;amp;referringTitle=Home"&gt;Exploring Recursive Common Table Expressions (CTE)&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DuplicateRows&amp;amp;referringTitle=Home"&gt;Find and/or Delete Duplicate Rows&lt;/a&gt; in a Table&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FindDataBetweenDates&amp;amp;referringTitle=Home"&gt;Find Rows of Data Between Two Dates&lt;/a&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FirstAvailableTimeslot&amp;amp;referringTitle=Home"&gt;Find First Available Timeslot&lt;/a&gt; for Scheduling &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FindMissingListItems&amp;amp;referringTitle=Home"&gt;Find the Missing Parts of a List &lt;/a&gt; of Requirements&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Implementation%20of%20DDL%20Trigger%20in%20SQL%20Server%202005&amp;amp;referringTitle=Home"&gt;Implementation of DDL Trigger in SQL Server 2005&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=IncrementAlphaNumericValues&amp;amp;referringTitle=Home"&gt;Increment an AlphaNumeric Value&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ISNULL_COALESCE&amp;amp;referringTitle=Home"&gt;Use ISNULL() and COALESCE()&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=GetAppLock&amp;amp;referringTitle=Home"&gt;Lock a Stored Procedure for Single Use Only&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=QueryBasedUponAbsenceOfData&amp;amp;referringTitle=Home"&gt;Query an Object Whose Result Set Depends Upon the Lack of Data In Another Object&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=StringArrayInput&amp;amp;referringTitle=Home"&gt;Pass and Handle a Delimited String&lt;/a&gt; similar to handling an Array() of Values&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PIVOTData&amp;amp;referringTitle=Home"&gt;PIVOT Data Using T-SQL&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=RankValuesInGroups&amp;amp;referringTitle=Home"&gt;Rank Values in Groups&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=NonDynamicSearch&amp;amp;referringTitle=Home"&gt;Search all or partial columns without Dynamic SQL&lt;/a&gt; while avoiding SQL Injection&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DynamicSearch&amp;amp;referringTitle=Home"&gt;Search all or partial columns with Dynamic SQL&lt;/a&gt; while avoiding SQL Injection&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SelectTopNbyGroup&amp;amp;referringTitle=Home"&gt;SELECT TOP n by Group&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=UNPIVOTData&amp;amp;referringTitle=Home"&gt;UNPIVOT Data Using T-SQL&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;Maintenance Queries&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ExpressBackups&amp;amp;referringTitle=Home"&gt;Automate Backups in SQL Express&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DetachUserDatabases&amp;amp;referringTitle=Home"&gt;Detach All User Databases&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LastBackUpDate&amp;amp;referringTitle=Home"&gt;Find Last BackUp Date Of All Databases On Your Server&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AgentLongRunning&amp;amp;referringTitle=Home"&gt;Find Long Running Agent Jobs&lt;/a&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LongRunningProcs&amp;amp;referringTitle=Home"&gt;Find the TOP n Longest Running Procedures&lt;/a&gt; (or Queries), Ordered by Total Impact on Server &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ExpressMaintenance&amp;amp;referringTitle=Home"&gt;Performing Common Maintenance Tasks in SQL Express&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=TransferLogins&amp;amp;referringTitle=Home"&gt;Transfer Logins to Another Server&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;Best Practices and Guidelines&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Best%20practices%20%2c%20Design%20and%20Development%20guidelines%20for%20Microsoft%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Best practices , Design and Development guidelines for Microsoft SQL Server&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;SQL Server Maintenance&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Log%20file%20growth%20in%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Log file growth in SQL Server&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Upgrading%20Steps%20to%20SQL%20Server%202005&amp;amp;referringTitle=Home"&gt;Upgrading Steps to SQL Server 2005&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Transfer%20Jobs%20and%20Logins%20using%20SSIS&amp;amp;referringTitle=Home"&gt;Transfer Jobs and Logins using SSIS&lt;/a&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AutomatedDBA&amp;amp;referringTitle=Home"&gt;Automating Common DBA Tasks&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;b&gt;SQL Server 2008&lt;/b&gt;&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Manage%20unstructured%20data%20using%20FILESTREAM%20Feature%20in%20SQL%20Server%202008&amp;amp;referringTitle=Home"&gt;Manage unstructured data using FILESTREAM Feature in SQL Server 2008&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;&lt;i&gt;How To&lt;/i&gt; Troubleshoot and Debug T-SQL Code&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Troubleshoot%20Deadlocking%20in%20SQL%20Server&amp;amp;referringTitle=Home"&gt;Troubleshoot Deadlocking in SQL Server&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Troubleshoot%20Deadlocking%20in%20SQL%20Server%202005%20using%20Profiler&amp;amp;referringTitle=Home"&gt;Troubleshoot Deadlocking in SQL Server 2005 using Profiler&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DeadlockAnatomy&amp;amp;referringTitle=Home"&gt;Understanding the Anatomy of a Deadlock&lt;/a&gt;.&lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Profiler&amp;amp;referringTitle=Home"&gt;Using the SQL Server Profiler&lt;/a&gt;.&lt;br /&gt; &lt;br /&gt;-----------------------------------------------------------------------------------------------------------------------------------------------------------------&lt;br /&gt;&lt;h5&gt;
&lt;b&gt;&lt;u&gt;Writing Transact-SQL Statements Tutorial&lt;/u&gt;&lt;/b&gt;
&lt;/h5&gt;&lt;a href="http://msdn2.microsoft.com/en-us/library/ms365303.aspx" class="externalLink"&gt;http://msdn2.microsoft.com/en-us/library/ms365303.aspx&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt;&lt;i&gt;Page Created&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=WikiGuidelines&amp;amp;referringTitle=Home"&gt; &lt;/a&gt;By: Arnie Rowland, Mar 12, 2008&lt;/i&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>JonathanKehayias</author><pubDate>Mon, 01 Dec 2008 21:51:18 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: Home 20081201P</guid></item><item><title>UPDATED WIKI: TestPage</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=TestPage&amp;version=69</link><description>&lt;div class="wikidoc"&gt;
&lt;h5&gt;
Test Environment
&lt;/h5&gt;You may create links here to your new Wiki page in order to work on it and keep it out of Public view until you are ready to make it 'public'. &lt;br /&gt;     Then when you are ready to make your page 'Public', note the Wiki PageName, and use it for the Wiki link on the referring page. &lt;br /&gt;     After your page is complete, and you have 'published' it, you may wish to remove the link from this page.&lt;br /&gt; &lt;br /&gt;     &lt;b&gt;WikiLink:  [Words Seen by User|YourWikiPage]&lt;/b&gt;&lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Transfer%20Jobs%20and%20Logins%20using%20SSIS&amp;amp;referringTitle=TestPage"&gt;Transfer Jobs and Logins using SSIS&lt;/a&gt; - Deepak&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Upgrading%20to%20SQL%20Server%202005&amp;amp;referringTitle=TestPage"&gt;Upgrading to SQL Server 2005&lt;/a&gt; - Deepak&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=Log%20file%20growth%20in%20SQL%20Server&amp;amp;referringTitle=TestPage"&gt;Log file growth in SQL Server&lt;/a&gt; - Deepak&lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DetachDatabaseVideo&amp;amp;referringTitle=TestPage"&gt;Detaching A Database with SSMS&lt;/a&gt; - Video Tutorial&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ListPrimaryForeignKeyInTable&amp;amp;referringTitle=TestPage"&gt;Find out all the primary key and foreign key constraints in a table&lt;/a&gt; - Suprotim Agarwal&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=analytics&amp;amp;referringTitle=TestPage"&gt;Testing out analytics&lt;/a&gt; - Suprotim&lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SQL%20Server%20Best%20Practices%20-%20Development&amp;amp;referringTitle=TestPage"&gt;SQL Server Best Practices - Development&lt;/a&gt; - Madhu&lt;br /&gt; &lt;br /&gt;This concept 'could' work -requires a counter.cgi hosted somewhere...&lt;br /&gt;(A bit tacky perhaps...)&lt;br /&gt;&lt;div class="video" style="text-align:center"&gt;
&lt;span class="player"&gt;&lt;object type="application/x-shockwave-flash" height="285" width="320" classid="CLSID:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"&gt;
&lt;param name="movie" value="http://www.indiana.edu/~counter/Count.cgi?df=MSDNMod-Page1.dat"&gt;

&lt;/param&gt;&lt;embed type="application/x-shockwave-flash" height="285" width="320" src="http://www.indiana.edu/~counter/Count.cgi?df=MSDNMod-Page1.dat" pluginspage="http://macromedia.com/go/getflashplayer" autoplay="false" autostart="false" /&gt;
&lt;/object&gt;&lt;/span&gt;&lt;br /&gt;&lt;span class="external"&gt;&lt;a href="http://www.indiana.edu/~counter/Count.cgi?df=MSDNMod-Page1.dat" target="_blank"&gt;Launch in another window&lt;/a&gt;&lt;/span&gt;
&lt;/div&gt;&lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ContributorBios&amp;amp;referringTitle=TestPage"&gt;Contributors&lt;/a&gt;&lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt; &lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt;&lt;i&gt;Page Created By: Arnie Rowland, Mar 16, 2008&lt;/i&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>JonathanKehayias</author><pubDate>Mon, 01 Dec 2008 21:50:43 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: TestPage 20081201P</guid></item><item><title>UPDATED WIKI: AutomatedDBA</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AutomatedDBA&amp;version=6</link><description>&lt;div class="wikidoc"&gt;
&lt;a name="Top"&gt;&lt;/a&gt;&lt;br /&gt;&lt;h4&gt;
How to Automate Common DBA Tasks
&lt;/h4&gt; &lt;br /&gt;&lt;h6&gt;
&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ContributorBios&amp;amp;referringTitle=AutomatedDBA&amp;amp;ANCHOR#JonathanKehayias"&gt;Jonathan Kehayias&lt;/a&gt;, Oct 21, 2008
&lt;/h6&gt; &lt;br /&gt;Database Administrators often spend hours each day doing the same repetitive tasks; checking Error Logs, Backups, Drive Space, Agent History, Job Logs, and other common “checklist” items.  It is fairly easy to automate these common tasks in SQL Server 2000, 2005 and 2008 using the tools that are already available in the Operating System and SQL Server.  To do this, a combination of TSQL, VBScript, WMI, and the SQL Server Agent and Windows Task Scheduler can be used.  This article will break the various items to monitor up into sub-articles to keep topics focused and separate.  The sub-articles will be in two classifications:&lt;br /&gt; &lt;br /&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="#TSQL"&gt;TSQL monitoring through SQL Agent&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="#VBScript"&gt;VBScript/WMI monitoring through Windows Task Scheduler&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt; &lt;br /&gt;&lt;a name="TSQL"&gt;&lt;/a&gt;&lt;br /&gt;&lt;h6&gt;
TSQL monitoring through SQL Agent
&lt;/h6&gt; &lt;br /&gt;Since DBA's monitor Database Servers, it is only natural that a majority of the monitoring that they do utilizes TSQL.  Since this is the case, the natural way to automate these tasks is with the use of the SQL Server Agent.  As a part of automation, the first item that will need to be setup is a method of providing notifications to the appropriate parties when an exception based event is found during the automated monitoring.  SQL Server 2000 is somewhat limited in its native notification abilities.  For security purposes the examples provided will not use SendMail which is native to SQL Server 2000, but instead a customized stored procedure based on the CDOSys stored procedure from Microsoft which does not require a IMAP client to be installed on the SQL Server.  For SQL Server 2005 and 2008, Database Mail should be used as it is native and the best option available.&lt;br /&gt; &lt;br /&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SQL2000CDOSysMail&amp;amp;referringTitle=AutomatedDBA"&gt;Configuring SQL Server 2000 Notification with CDOSys&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DatabaseMailConfig&amp;amp;referringTitle=AutomatedDBA"&gt;Configuring SQL Server 2005/2008 Database Mail&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt; &lt;br /&gt;Once a method of providing notifications is configured it is possible to begin monitoring the SQL Server with TSQL scripts.  Items that can be easily monitored with TSQL include:&lt;br /&gt; &lt;br /&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FileSpaceMon&amp;amp;referringTitle=AutomatedDBA"&gt;Monitor free space in the database files&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DiskSpaceMon&amp;amp;referringTitle=AutomatedDBA"&gt;Monitor free space on the server hard disks&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ErrorLogMon&amp;amp;referringTitle=AutomatedDBA"&gt;Monitor the SQL Server Error Log&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=LongRunningJobMon&amp;amp;referringTitle=AutomatedDBA"&gt;Monitor long running SQL Agent Jobs&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=FailedJobMon&amp;amp;referringTitle=AutomatedDBA"&gt;Monitor failed SQL Agent Jobs&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt; &lt;br /&gt;&lt;a href="#Top"&gt;Return to Top&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;a name="VBScript"&gt;&lt;/a&gt;&lt;br /&gt;&lt;h6&gt;
VBScript/WMI monitoring through Windows Task Scheduler
&lt;/h6&gt; &lt;br /&gt;Along with monitoring for events internal to SQL Server, it is also important for to monitor items external to SQL Server.  Since Windows Server 2000, VBScript and WMI have been available, and have been used for automating various tasks for administrators.  VBScript can use the CDO object to send email natively which makes it a very good way to provide notifications of exceptions found.  Items that can be monitored with VBScript and WMI include:&lt;br /&gt; &lt;br /&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ServiceStatusMon&amp;amp;referringTitle=AutomatedDBA"&gt;Monitor Service Status&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SystemLogMon&amp;amp;referringTitle=AutomatedDBA"&gt;Monitor System Event Logs&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ProcessInfoMon&amp;amp;referringTitle=AutomatedDBA"&gt;Monitor Running Process Information&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt; &lt;br /&gt;&lt;a href="#Top"&gt;Return to Top&lt;/a&gt;&lt;br /&gt; &lt;br /&gt; &lt;br /&gt;&lt;h4&gt;
For additional information please see:
&lt;/h4&gt; &lt;br /&gt;&lt;h5&gt;
DBA Checklist
&lt;/h5&gt;&lt;a href="http://blogs.msdn.com/buckwoody/archive/2008/03/28/real-world-dba-episode-5-the-dba-checklist.aspx" class="externalLink"&gt;http://blogs.msdn.com/buckwoody/archive/2008/03/28/real-world-dba-episode-5-the-dba-checklist.aspx&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;&lt;h5&gt;
Automating DBA Processes (TechEd 2008)
&lt;/h5&gt;&lt;a href="http://mfile.akamai.com/14853/wmv/microsofttec.download.akamai.com/14853/TechEdOnline/Videos/08_NA_ITP_TEOPanel_69_low.asx" class="externalLink"&gt;http://mfile.akamai.com/14853/wmv/microsofttec.download.akamai.com/14853/TechEdOnline/Videos/08_NA_ITP_TEOPanel_69_low.asx&lt;span class="externalLinkIcon"&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt; &lt;br /&gt; &lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt;&lt;i&gt;Page Created By: Jonathan Kehayias, Oct 21, 2008&lt;/i&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>JonathanKehayias</author><pubDate>Mon, 01 Dec 2008 21:49:54 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: AutomatedDBA 20081201P</guid></item><item><title>UPDATED WIKI: ProcessInfoMon</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ProcessInfoMon&amp;version=4</link><description>&lt;div class="wikidoc"&gt;
&lt;a name="Top"&gt;&lt;/a&gt;&lt;br /&gt;&lt;h4&gt;
Monitor Running Process Information 
&lt;/h4&gt; &lt;br /&gt;&lt;h6&gt;
&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ContributorBios&amp;amp;referringTitle=ProcessInfoMon&amp;amp;ANCHOR#JonathanKehayias"&gt;Jonathan Kehayias&lt;/a&gt;, October 28, 2008
&lt;/h6&gt; &lt;br /&gt;The following script will generate a report of information for the running SQL processes on a server in a text file output.&lt;br /&gt; &lt;br /&gt; &lt;br /&gt;&lt;h6&gt;
RunningProcessMonitor.vbs Script
&lt;/h6&gt;&lt;pre&gt;
 
on error resume next
 
Set iFSO = CreateObject(&amp;quot;Scripting.FilesyStemObject&amp;quot;)
Set oFSO = CreateObject(&amp;quot;Scripting.FilesyStemObject&amp;quot;)
Outputfile=&amp;quot;RunningProcessInformation.txt&amp;quot;
InputFile=&amp;quot;Serverlist.txt&amp;quot;
 
Set ifile = iFSO.OpenTextFile(inputfile)
Set ofile = ofso.createTextFile(OutputFile, True)
 
Do until ifile.AtEndOfLine
 
	strComputer = ifile.ReadLine
 
 
	Set objWMIService = GetObject(&amp;quot;winmgmts:\\&amp;quot; &amp;amp; strComputer &amp;amp; &amp;quot;\root\cimv2&amp;quot;)
	Set colProcessList = objWMIService.ExecQuery (&amp;quot;Select * from Win32_Service WHERE Name LIKE '%SQL%'&amp;quot;)
 
 
For Each objProcess in colProcessList
	ofile.writeline  &amp;quot;	Name: &amp;quot; &amp;amp; objProcess.Name
	ofile.writeline  &amp;quot;	Started:&amp;quot; &amp;amp; objProcess.Started 
	ofile.writeline  &amp;quot;	Status: &amp;quot; &amp;amp; objProcess.Status
	ofile.writeline  &amp;quot;	State: &amp;quot; &amp;amp; objProcess.State
	ofile.writeline  &amp;quot;	Process ID: &amp;quot; &amp;amp; objProcess.ProcessID 
	ofile.writeline  &amp;quot;	Thread Count: &amp;quot; &amp;amp; objProcess.ThreadCount 
	ofile.writeline  &amp;quot;	Page File Size: &amp;quot; &amp;amp; objProcess.PageFileUsage 
	ofile.writeline  &amp;quot;	Page Faults: &amp;quot; &amp;amp; objProcess.PageFaults 
	ofile.writeline  &amp;quot;	Working Set Size: &amp;quot; &amp;amp; objProcess.WorkingSetSize 
	ofile.writeline  &amp;quot;&amp;quot;
Next
 
Loop
   
&lt;/pre&gt;&lt;a href="#Top"&gt;Return to Top&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;You can find the sample ServerList.txt file &lt;a href="javascript:window.location.href='http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=SQLExamples&amp;amp;DownloadId=4024';"&gt;ServerList.txt&lt;/a&gt;.&lt;br /&gt; &lt;br /&gt;This is article is part of a series on Automating Common DBA tasks in SQL Server.  To see the full series see: &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AutomatedDBA&amp;amp;referringTitle=ProcessInfoMon"&gt;Automating Common DBA Tasks&lt;/a&gt; &lt;br /&gt; &lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt;&lt;i&gt;Page Created By: Jonathan Kehayias, Oct 28, 2008&lt;/i&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>JonathanKehayias</author><pubDate>Mon, 01 Dec 2008 21:49:19 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: ProcessInfoMon 20081201P</guid></item><item><title>UPDATED WIKI: ErrorLogMon</title><link>http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ErrorLogMon&amp;version=7</link><description>&lt;div class="wikidoc"&gt;
&lt;a name="Top"&gt;&lt;/a&gt;&lt;br /&gt;&lt;h4&gt;
Monitor the SQL Server Error Log
&lt;/h4&gt; &lt;br /&gt;&lt;h6&gt;
&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ContributorBios&amp;amp;referringTitle=ErrorLogMon&amp;amp;ANCHOR#JonathanKehayias"&gt;Jonathan Kehayias&lt;/a&gt;, October 28, 2008
&lt;/h6&gt; &lt;br /&gt;One of the most important things that a DBA could monitor is the SQL Server Error Log.  SQL Server will log almost every event of interest to a DBA for early problem identification to the Error Log.  This includes failed logins, Backup completion by database, and backup failures by database, the end of recovery after a restart, DBCC Events, reconfiguration of server or database options, non-yielding schedulers, stack dumps, autogrowth failures, delayed IO events, and trace flag output if the flags have been turned on.  Developers can also have errors in code execution be logged to the Error Log by using the WITH LOG option of RAISERROR.  The amount of information that a DBA can get from the Error Log can be quite overwhelming.  For this reason, non-critical events and events of non-interest should be filtered from the log data when generating automated notifications.&lt;br /&gt; &lt;br /&gt;The following stored procedure will read the Error Log.  There are three parameters which control what log file is actually read, whether the output is to the Results Grid or to email notifications, and the number of minutes from the runtime to look backwards for events.  The procedure can be called without any of the parameters since all of them have default values set for them, and it will generate email notifications for any event not filtered out for the last 5 minutes in the active Error Log.&lt;br /&gt; &lt;br /&gt;&lt;h6&gt;
GetErrorLogEvents Stored Procedure
&lt;/h6&gt;&lt;pre&gt;
 
CREATE PROCEDURE [dbo].[GetErrorLogEvents] (@LogNumber int = 0, @runlocal int = 0, @NumberOfMinutes int = 5)
AS
--  Test Variables
--declare @Lognumber smallint
--declare @runlocal bit
--set @Lognumber = 0
--set @runlocal = 0
--
 
declare @count  smallint,
        @SQL    varchar(1000),
        @output varchar(255),
		@runtime datetime,
		@sqlversion varchar(10)
 
set @count  = 0
set @SQL    = ''
set @output = ''
set @sqlversion = rtrim(ltrim(substring(@@version, 22, 5)))
set @runtime = getdate()
 
if @runlocal = 1
	set @runtime = getdate()-100
 
 
if object_id('tempdb..#errors') is not null
begin
   drop table #errors
end
 
CREATE TABLE #errors
(
	RowID int IDENTITY PRIMARY KEY,
	EntryTime datetime,
	source varchar(50),
	LogEntry varchar(4000)
)
 
if @@version like '%2000%'
begin
	if object_id('tempdb..#errorlog') is not null
	begin
	   drop table #errorlog
	end
 
	create table #errorlog
	(
	   log_id          int identity primary key, 
	   alert           char(5) default ' ',
	   logentry       varchar(4000),
	   continuationrow int
	)
 
	select @SQL = 'exec master..Sp_readerrorlog ' + convert(varchar(3),@lognumber)
	insert into #errorlog (logentry, continuationrow)
	execute (@SQL)
 
	declare @loop int
	declare @text varchar(3000)
 
	select @loop = max(log_id)
	from #errorlog
	where continuationrow = 1
 
	while @loop is not null
	begin
 
	select @text = null
 
	select @text = logentry
	from #errorlog
	where log_id = @loop
 
	update #errorlog
	set logentry = logentry + @text
	where log_id = @loop - 1
 
	delete #errorlog where log_id = @loop
 
	select @loop = max(log_id)
	from #errorlog
	where continuationrow = 1
	and log_id &amp;lt; @loop
 
	end
	   
	-- Mark interesting entries
	update #errorlog
	   set alert = '----&amp;gt;'
	 where (logentry like '%err%'
		or logentry like '%warn%'
		or logentry like '%kill%'
		or logentry like '%dead%'
		or logentry like '%cannot%'
		or logentry like '%could%'
		or logentry like '%fail%'
		or logentry like '%not%'
		or logentry like '%stop%'
		or logentry like '%terminate%'
		or logentry like '%bypass%'
		or logentry like '%roll%'
		or logentry like '%truncate%'
		or logentry like '%upgrade%'
		or logentry like '%victim%'
		or logentry like '%recover%'
		or logentry like '%IO requests taking longer than%')
		AND logentry not like '%errorlog%'
		AND logentry not like '%dbcc%'
 
	INSERT INTO #errors (entrytime, source, logentry)
	-- Show each interesting entry
	select
		   CASE WHEN left(logentry, 3) = '200' THEN convert(datetime, substring(logentry, 0, 23))
				ELSE NULL 
			END AS EntryTime,
		   CASE WHEN left(logentry, 3) = '200' THEN substring(logentry, 24, 10)
				ELSE NULL 
			END AS Source,
		   CASE WHEN left(logentry, 3) = '200' THEN substring(logentry, 34, 300)
				ELSE logentry 
			END AS LogEntry
	  from #errorlog
	where Alert = '----&amp;gt;'
 
	IF @RunLocal = 1
	BEGIN
		select * from #errorlog
	END
 
 
end -- SQL 2000
else -- SQL 2005
begin
 
	select @SQL = 'exec master..xp_readerrorlog ' + convert(varchar(3),@lognumber)
	insert into #errors (entrytime, source, logentry)
	execute (@SQL)
 
delete #errors 
where (logentry not like '%err%'
		AND logentry not like '%warn%'
		AND logentry not like '%kill%'
		AND logentry not like '%dead%'
		AND logentry not like '%cannot%'
		AND logentry not like '%could%'
		AND logentry not like '%fail%'
		AND logentry not like '%not%'
		AND logentry not like '%stop%'
		AND logentry not like '%terminate%'
		AND logentry not like '%bypass%'
		AND logentry not like '%roll%'
		AND logentry not like '%truncate%'
		AND logentry not like '%upgrade%'
		AND logentry not like '%victim%'
		AND logentry not like '%recover%'
		AND logentry not like '%IO requests taking longer than%')
		OR logentry like '%errorlog%'
		OR logentry like '%dbcc%'
 
END
 
DELETE #Errors 
WHERE EntryTime IS NULL OR EntryTime &amp;lt;  dateadd(mi, (-1*@NumberOfMinutes), @runtime)
 
-- If local only return the events table back to the Results Grid
IF @RunLocal = 1
BEGIN
	SELECT *
	FROM #errors
END
ELSE -- Insert the errors into the SystemEvents table to trigger notification.
BEGIN
 
	CREATE TABLE #Exceptions
	(
		RowID int identity Primary Key,
		LogEntry varchar(4000),
		EntryCount int,
		LastOccurence datetime
	)
 
 
	INSERT INTO #Exceptions (LogEntry, EntryCount, LastOccurence)
	SELECT LogEntry, count(*), max(EntryTime)
	FROM #Errors
	GROUP BY LogEntry
 
		DECLARE @Loop2 int
		DECLARE @Subject varchar(100)
		DECLARE @strMsg varchar(4000)
 
		SELECT @Subject = 'SQL Monitor Alert: ' + @@servername
 
		SELECT @Loop2 = min(RowID)
		FROM #Exceptions
 
		WHILE @Loop2 IS NOT NULL
		BEGIN
 
			SELECT 	@strMsg =  convert(char(15),'LogEntry:') + isnull(LogEntry, 'Unknown') + char(10) +
					convert(char(15),'EventTime:') + convert(varchar, LastOccurence) + char(10) +
					convert(char(15),'') + char(10) +
					convert(char(15),'') + 'This error has occured '+convert(varchar, EntryCount)+' times.'
			FROM #Exceptions
			WHERE RowID = @Loop2
 
			EXEC dbo.SendEmailNotification @Subject, @strMsg
 
			SELECT @Loop2 = min(RowID)
			FROM #Exceptions
			WHERE RowID &amp;gt; @Loop2
 
		END
 
END
 
DROP TABLE #Exceptions
DROP TABLE #Errors
   
&lt;/pre&gt;&lt;a href="#Top"&gt;Return to Top&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;Since SQL Server only starts a new log natively when the Service is restarted, the log files can grow to be very large in size, depending on the number of errors logged, and the time between service/server restarts.  This can impact the performance of the above stored procedure if the log is large enough.  To mitigate against this, the Error Log can be rolled over nightly by calling the following TSQL command in a SQL Agent Job.  &lt;br /&gt; &lt;br /&gt;&lt;h6&gt;
Rollover the SQL Server Error Log with DBCC
&lt;/h6&gt;&lt;pre&gt;
 
USE [master]
GO
DBCC ERRORLOG
GO
 
&lt;/pre&gt;&lt;a href="#Top"&gt;Return to Top&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;This can also be accomplished with sp_cycle_errorlog&lt;br /&gt; &lt;br /&gt;&lt;h6&gt;
Rollover the SQL Server Error Log with sp_cycle_errorlog
&lt;/h6&gt;&lt;pre&gt;
 
USE [master]
GO
sp_cycle_errorlog
GO
 
&lt;/pre&gt;&lt;a href="#Top"&gt;Return to Top&lt;/a&gt;&lt;br /&gt;However, this may cause the logs to flush off of the server too fast under the default log retention of six Error Logs.  When performing a nightly rollover of the Error Logs, it is recommended that the default log retention be set to retain the needed number of Logs on the server to meet business and regulatory requirements.  This can be done using the following TSQL command:&lt;br /&gt; &lt;br /&gt;&lt;h6&gt;
Change Error Log Retention Value
&lt;/h6&gt;&lt;pre&gt;
 
USE [master]
GO
DECLARE @NumberOfLogs int
SET @NumberOfLogs = 28
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'NumErrorLogs', REG_DWORD, @NumberOfLogs
GO
 
&lt;/pre&gt;&lt;a href="#Top"&gt;Return to Top&lt;/a&gt;&lt;br /&gt; &lt;br /&gt;This procedure uses the SendNotificationEmail wrapper procedure to create a standard set of code that can be used on all editions of SQL Server.  This wrapper stored procedure can be found on one of the following articles:&lt;br /&gt; &lt;br /&gt;&lt;ul&gt;
&lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SQL2000CDOSysMail&amp;amp;referringTitle=ErrorLogMon"&gt;Configuring SQL Server 2000 Notification with CDOSys&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DatabaseMailConfig&amp;amp;referringTitle=ErrorLogMon"&gt;Configuring SQL Server 2005/2008 Database Mail&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt; &lt;br /&gt;This is article is part of a series on Automating Common DBA tasks in SQL Server.  To see the full series see: &lt;a href="http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=AutomatedDBA&amp;amp;referringTitle=ErrorLogMon"&gt;Automating Common DBA Tasks&lt;/a&gt; &lt;br /&gt; &lt;br /&gt;___________________________________________________________________________________________________________________&lt;br /&gt;&lt;i&gt;Page Created By: Jonathan Kehayias, Oct 28, 2008&lt;/i&gt;&lt;br /&gt;
&lt;/div&gt;</description><author>JonathanKehayias</author><pubDate>Mon, 01 Dec 2008 21:43:27 GMT</pubDate><guid isPermaLink="false">UPDATED WIKI: ErrorLogMon 20081201P</guid></item></channel></rss>