Showing posts with label General. Show all posts
Showing posts with label General. Show all posts

Thursday, September 3, 2009

(CSS) - Updated Support Policy for Virtualization of SQL Server

Microsoft updated the Support Policy for running SQL Server Virtualized today.  The CSS Team Blog has a post that provides a quick overview of what's changed as well as a link to the new policy:

http://blogs.msdn.com/psssql/archive/2009/09/03/another-update-for-the-support-policy-for-virtualization-for-sql-server.aspx

Now I haven't personally looked at the SVVP approved vendor list in a long time but I decided to take a glance today at it, and there are a bunch of new approved platforms:

http://www.windowsservercatalog.com/results.aspx?&bCatID=1521&cpID=0&avc=0&ava=0&avq=0&OR=1&PGS=25

The key topics to make note of in the updated policy which can be found on the following KB Article are listed in the Restrictions and Limitations and include the inclusion of Guest Failover Clustering Support if you are on Windows Server 2008 and meet the requirements of Windows Server 2008 Failover Clustering, and the lack of support for Virtualization Snapshots.

Thursday, January 8, 2009

Other Blogs that you should be Watching

I committed to blogging about other SQL blogs in the community after Jason Massie gave me a bump on his blog.  So this week I spent some time reading over some of the blogs in my reader and finding ones that don't have many posts yet, but have demonstrated a sustained interest in blogging somewhat frequently.

TJay Belt's Thoughts - TJay Belt

TJay started blogging consistently before PASS 2008, and has quite an amazing blog roll on his site.  I made a reminder to come back to it and look at what feeds he might have of interest that I don't yet.

StraightPath Solutions - Mike Walsh

I usually don't recommend business based blogs, but Mike Walsh dedicates a good bit of time to helping people on the forums and Newsgroups for free, and he commented on a post here this week so I had to check out his blog the other day anyway.

Facility 9 - Jeremiah Peschka

I know Jeremiah from Twitter, and he is always doing performance tuning it would seem from his Tweets, but his blog covers more than just that. 

If you have a blog you'd like reviewed, send me an email, and I'll add it to my feed reader and see what you are all about.  I think that almost every blog post I see is interesting in one way or another, so even if I don't put you in a post like this, I will be subscribed to your blog.  :-)

Wednesday, December 31, 2008

Another Year Gone - 2008 in Review

It is really amazing to look back on 2008, and see what all I have accomplished both personally as well as professionally.  At the start of 2008, I was completely unknown in the SQL Server Community and online.  I had asked a grand total of 4 questions on the forums and had never once answer someone else's question.  I had never written a blog post, or technical article online.

To recap this year, I have replied over 5000 times to questions on MSDN forums, SQL Server Central Forums, and Microsoft Newsgroups.  I have posted 128 blog posts, written 2 articles for SQL Server Central and 28 articles on the SQL Examples Site on Code Project.  I also did a Live Meeting for the PASS DBA Special Interest Group, and presented at 3 user groups and 4 different conferences this year. 

If you are reading this and you haven't done a presentation, written a blog post, or online article, then hopefully this will motivate you to get your start.  If you think you don't know enough, or that people won't be interested, then try and do the presentation at your local user group first.  You'll be surprised with the outcome and amount of interest that there may be, I can almost guarantee it. 

Tuesday, December 23, 2008

Other Blogs that you should be Watching

Following my blog post from yesterday where I listed the major blogs from the SQL Server Team that you should follow, today, I am going to list some "unknown" blogs that you might consider following.  This post is more of a "pay it forward" type of post since Jason Massie, did a similar post and listed my blog in his list of ten blogs to follow and it tripled traffic to my blog. 

In no particular order:

Aaron Alton is a rising star in the SQL Server Community, and a fellow Moderator in the MSDN SQL Server Forums.  His blog can be found at  http://thehobt.blogspot.com.  Look to find posts similar to mine where the focus is around questions commonly asked on the MSDN forums.

Sankar Reddy is another Moderator from the MSDN SQL Server Forums as well who blogs at http://sankarreddy.spaces.live.com/.  Again his posts should be similar in nature to my own, and follow common problems seen in the community.

Gail Shaw is a fellow MVP, and a consistent top performer on the SQL Server Central forums.  She covered the PASS Summit live from PASS Summit, and is definitely worth following.

Monday, December 22, 2008

Blogs you should be watching

If you are reading this, I hope that you are watching my blog, or that you have subscribed to it in a RSS feed reader.  However, if you haven't or you don't that is no matter, and isn't the real topic of this posting.  The real purpose of this post is to make you aware of a specific set of blogs at Microsoft that you should be following if SQL Server is your primary area of responsibility.

Number one of the list has to be the Microsoft SQL Server Release Services blog.  This is the primary location to find out about new releases happening regarding SQL Server, from major releases, to service packs and cumulative updates, it is announced here.  This is how I stat up to date with when releases occur for SQL Server.

Number two on the list would be the CSS SQL Server Engineers blog for SQL Server.  A few people post here, all from the Customer Service and Support team for SQL Server, but the posts are generally centered around problems that the CSS team is seeing in their day to day work.  You can get a good heads up on solutions to popular problems by simply monitoring this blog.

Number three on the list would be the SQL Server Storage Engine blog.  This is one of my favorite SQL Server Team blogs, mainly because it has to deal with the side of SQL that I deal with primarily.  However, in the grand scheme of things, for most people, it is probably the third most important blog to watch behind the above two.

If you are a developer, and not a DBA, swap the above number three with the following number four which is SQL Programmability & API Development Team Blog.  This blog has pointers about how to use the programmability features of SQL Server, as well as how to performance tune code, and the SQL instance for specific scenarios.

Number five on my list would be the Microsoft SQL ISV Program Management Team blog.  A note here is that if you watch the SQL Programmability & API Development Team Blog as well, you will probably see a bit of overlap since these two teams seem to work hand in hand with each other to solve ISV problems at times.  The ISV team may also solve a problem that the Programmability team finds interesting enough to share with their followers and they will repost it, but there are non-overlapping posts between the two that make both worth following.

The last SQL Team blog to watch is the SQL Server SQLOS team blog.  I place this one last only because it doesn't have the posting frequency that other blogs do. The information on this blog is just as important, it just isn't updated with any regular frequency.  However, if an update is posted, you probably would be good to know about it.

That's all folks.  If you are not following the above blogs, I highly recommend it.

Monday, December 15, 2008

Drop All Indexes and Stats in one Script

I am not sure why someone would want to do this, but it was asked on the forums, and I figured I would post the code I created to perform such a nightmarish operation.  As with any post that I make providing code that could be potentially damaging and dangerous, if you use it, you do so at your own risk.  Don't send me emails complaining that you got fired for deleting all the indexes with the scripts on this post.  I am not going to be able to help you fix it, and my recommendation is going to be restore a backup, and start scripting them all off if you still have a job.

SQL Server 2000 Code

DECLARE @ownername SYSNAME
DECLARE
@tablename SYSNAME
DECLARE
@indexname SYSNAME
DECLARE
@sql NVARCHAR(4000)
DECLARE dropindexes CURSOR FOR

SELECT
sysindexes.name, sysobjects.name, sysusers.name
FROM sysindexes
JOIN sysobjects ON sysindexes.id = sysobjects.id
JOIN sysusers ON sysobjects.uid = sysusers.uid
WHERE indid > 0
 
AND indid < 255
 
AND INDEXPROPERTY(sysobjects.id, sysindexes.name, 'IsStatistics') = 0
 
AND sysobjects.TYPE = N'U'
 
AND NOT EXISTS (SELECT 1 FROM sysobjects WHERE sysobjects.name = sysindexes.name)
ORDER BY sysindexes.id, indid DESC

OPEN
dropindexes
FETCH NEXT FROM dropindexes INTO @indexname, @tablename, @ownername
WHILE @@fetch_status = 0
BEGIN
  SET
@sql = N'DROP INDEX '+QUOTENAME(@ownername)+'.'+QUOTENAME(@tablename)+'.'+QUOTENAME(@indexname)
 
PRINT @sql
 
EXEC sp_executesql @sql  
 
FETCH NEXT FROM dropindexes INTO @indexname, @tablename, @ownername
END
CLOSE
dropindexes
DEALLOCATE dropindexes

GO
DECLARE @ownername SYSNAME
DECLARE
@tablename SYSNAME
DECLARE
@statsname SYSNAME
DECLARE
@sql NVARCHAR(4000)
DECLARE dropstats CURSOR FOR

SELECT
sysindexes.name, sysobjects.name, sysusers.name
FROM sysindexes
JOIN sysobjects ON sysindexes.id = sysobjects.id
JOIN sysusers ON sysobjects.uid = sysusers.uid
WHERE indid > 0
 
AND indid < 255
 
AND INDEXPROPERTY(sysobjects.id, sysindexes.name, 'IsStatistics') = 1
 
AND sysobjects.TYPE = N'U';

OPEN dropstats
FETCH NEXT FROM dropstats INTO @statsname, @tablename, @ownername
WHILE @@fetch_status = 0
BEGIN
  SET
@sql = N'DROP STATISTICS '+QUOTENAME(@ownername)+'.'+QUOTENAME(@tablename)+'.'+QUOTENAME(@statsname)
 
EXEC sp_executesql @sql  
 
--PRINT @sql
 
FETCH NEXT FROM dropstats INTO @statsname, @tablename, @ownername
END
CLOSE
dropstats
DEALLOCATE dropstats

The above script will work for SQL 2005 and 2008 also, but only because compatibility views have been carried forward in code by Microsoft. The correct code for doing this in SQL 2005 and 2008 is as follows:

SQL Server 2005/2008

DECLARE @ownername SYSNAME
DECLARE
@tablename SYSNAME
DECLARE
@indexname SYSNAME
DECLARE
@sql NVARCHAR(4000)
DECLARE dropindexes CURSOR FOR

SELECT
indexes.name, objects.name, schemas.name
FROM sys.indexes
JOIN sys.objects ON indexes.OBJECT_ID = objects.OBJECT_ID
JOIN sys.schemas ON objects.schema_id = schemas.schema_id
WHERE indexes.index_id > 0
 
AND indexes.index_id < 255
 
AND objects.is_ms_shipped = 0
 
AND NOT EXISTS (SELECT 1 FROM sys.objects WHERE objects.name = indexes.name)
ORDER BY objects.OBJECT_ID, indexes.index_id DESC


SELECT
* FROM sys.stats
OPEN dropindexes
FETCH NEXT FROM dropindexes INTO @indexname, @tablename, @ownername
WHILE @@fetch_status = 0
BEGIN
  SET
@sql = N'DROP INDEX '+QUOTENAME(@ownername)+'.'+QUOTENAME(@tablename)+'.'+QUOTENAME(@indexname)
 
PRINT @sql
 
EXEC sp_executesql @sql  
 
FETCH NEXT FROM dropindexes INTO @indexname, @tablename, @ownername
END
CLOSE
dropindexes
DEALLOCATE dropindexes

GO
DECLARE @ownername SYSNAME
DECLARE
@tablename SYSNAME
DECLARE
@statsname SYSNAME
DECLARE
@sql NVARCHAR(4000)
DECLARE dropstats CURSOR FOR

SELECT
stats.name, objects.name, schemas.name
FROM sys.stats
JOIN sys.objects ON stats.OBJECT_ID = objects.OBJECT_ID
JOIN sys.schemas ON objects.schema_id = schemas.schema_id
WHERE stats.stats_id > 0
 
AND stats.stats_id < 255
 
AND objects.is_ms_shipped = 0
ORDER BY objects.OBJECT_ID, stats.stats_id DESC

OPEN
dropstats
FETCH NEXT FROM dropstats INTO @statsname, @tablename, @ownername
WHILE @@fetch_status = 0
BEGIN
  SET
@sql = N'DROP STATISTICS '+QUOTENAME(@ownername)+'.'+QUOTENAME(@tablename)+'.'+QUOTENAME(@statsname)
 
EXEC sp_executesql @sql  
 
--PRINT @sql
 
FETCH NEXT FROM dropstats INTO @statsname, @tablename, @ownername
END
CLOSE
dropstats
DEALLOCATE dropstats

Hope it helps someone out.

Monday, December 8, 2008

SET ROWCOUNT functionality changes

Lately it seems to me like I need to put some time and effort into actually reading the updated versions of the Books Online to learn about what I have missed, either as changes coming, or changes that have occured. Take for instance SET ROWCOUNT. I learned how to use this in SQL 2000, and it was by someone else, so I have never actually read the BOL entries for it, until recently.

If you look back at my first post on the Transaction Log - Managing Size, one of the examples I posted for batched deletes uses SET ROWCOUNT to limit the size of the delete batches. This is actually a commonly posted example on the forums, and other places online, and in answering a question on the Newsgroups, I posted this same example as a response. Not long after another person on the Newsgroups, Plamen Ratchev, who pointed out that SET ROWCOUNT will cease to function for INSERT, DELETE, and UPDATE in a future release of SQL Server.

No problem, although this was news to me, so I took a peak at the SQL Server 2008 BOL topic for SET ROWCOUNT and sure enough it is documented in there:

Using SET ROWCOUNT will not affect DELETE, INSERT, and UPDATE statements in the next release of SQL Server. Do not use SET ROWCOUNT with DELETE, INSERT, and UPDATE statements in new development work, and plan to modify applications that currently use it. Also, for DELETE, INSERT, and UPDATE statements that currently use SET ROWCOUNT, we recommend that you rewrite them to use the TOP syntax.

So I looked back in time to see where this was introduced, and it actually is listed in the SQL Server 2000 BOL topic as well. So it must be being carried forward due to compatibility issues and the amount of code that could be potentially impacted because this really is a common thing to find online or in code. I did a quick search of the code in some of our vendors databases, and almost every one that does a purge job uses SET ROWCOUNT in them. Not to worry, I was nice and emailed a few of them that I had contacts with the DBA support/development staff members to let them know about it so they can update it in a future service pack if they choose.

Wednesday, December 3, 2008

Estimating the Size of your Database Backups

I think I have answered a dozen or so questions regarding how to estimate the size of database backups without running the backup in the last few months on the Forums.  It is really quite simple to estimate how large a backup will be for a database.  The sp_spaceused system stored procedure will show how much reserved space there is in the database.  This is roughly equivalent to the size that the backup will be when it completes.

USE SQLCLR_Examples
GO
EXEC sp_spaceused @updateusage = 'true'
           

database_name                         database_size      unallocated space

------------------------------------- ------------------ ------------------

SQLCLR_Examples                       6031.50 MB         4326.55 MB

reserved           data               index_size         unused

------------------ ------------------ ------------------ ------------------

988624 KB          944216 KB          43200 KB           1208 KB

I create a backup with the following command:

BACKUP DATABASE [SQLCLR_Examples]
TO DISK = N'D:\SQLCLR_Examples.bak'
WITH NOFORMAT, NOINIT,
NAME = N'SQLCLR_Examples-Full Database Backup',
SKIP, NOREWIND, NOUNLOAD, STATS = 10

Then look at its size with the following command:

SELECT CONVERT(VARCHAR, CONVERT(DECIMAL(18,1), backup_size/1024))+ ' KB' [Backup Size]
FROM msdb.dbo.backupset
WHERE database_name = 'SQLCLR_Examples'
 
AND backup_finish_date > DATEADD(hh, -1, GETDATE())

Backup Size

---------------------------------

993573.5 KB

So you can see from this demonstration that the size of the backup is roughly equal to the reserved space in the database from sp_spaceused.  The updateusage parameter is sometimes needed to account for changes that have occured but are not yet reflected in the usage stats for the database.

Tuesday, December 2, 2008

Find databases missing a backup

If you manage multiple servers, and you don't have complete control over your database backups, then you need to be checking regularly that all of your databases are indeed being backed up. With SQL Server 2008, Policy Based Management makes this very easy to do. There is a Microsoft Books Online entry for this:

Monitoring and Enforcing Best Practices by Using Policy-Based Management

You don't have to be on a SQL Server 2008 server to use PBM. You can actually use it manually from SQL Server Management Studio by downloading the Express Edition of 2008 with Tools. However, if you are not taking the leap to SQL Server 2008 anytime soon, you still need to know how to monitor this. You can do so with a simple TSQL Query using a few system tables:


SELECT database_name, last_backup
    
FROM
    
(  
    
SELECT database_name, MAX(backup_finish_date) [last_backup]
        
FROM msdb.dbo.backupset
                
JOIN MASTER..sysdatabases d ON database_name = d.name
        
WHERE TYPE = 'd'
        
GROUP BY database_name
        
UNION ALL
    
SELECT d.name, NULL
        
FROM MASTER..sysdatabases d
        
WHERE NOT EXISTS (
        
SELECT 1
            
FROM msdb..backupset
            
WHERE d.name = database_name)
    )
AS tab
    
WHERE tab.last_backup < GETDATE()-14
        
OR tab.last_backup IS NULL

I intentionally use the legacy table sysdatabases table so that this script works across all platforms exactly the same way. If you were to download the Express Edition of SQL Server 2008 Management Studio, you could hit all of your SQL Servers regardless of edition, (2000, 2005 and 2008) with this on a multi-server query. Want to know how to do that, see my article on this
Multiple Server Queries with SSMS 2008 - SQL Server Central

I know that is kind of a shameless plug, but it is what it is.

Monday, December 1, 2008

Automating Common DBA Tasks Complete Series

I have blogged about this briefly in the past, but I am going to post a full link set to all of the code that I use to automate monitoring of my production database servers. All of the code is available on the MSDN Forums SQL Examples Wiki site, and I might back post the series in my blog at a later date but I may not.  The entire series is sub categorized under the main article Automating Common DBA Tasks.

Inside this the code is sub-categorized into TSQL monitoring through SQL Agent:

Configuring SQL Server 2000 Notification with CDOSys
Configuring SQL Server 2005/2008 Database Mail
Log file growth in SQL Server
Monitor free space in the database files
Monitor free space on the server hard disks
Monitor the SQL Server Error Log
Monitor long running SQL Agent Jobs
Monitor failed SQL Agent Jobs

and VBScript/WMI monitoring through Windows Task Scheduler:

Monitor Service Status
Monitor System Event Logs
Monitor Running Process Information

Please feel free to contact me and let me know if you have any issues with using this code.  It is not exactly identical to the code in my production servers since there is some proprietary information in my own production code, but the changes are only slightly minor, and I have done my best to test and validate the code I published, and it all should work as intended.

Speaking at Tampa Code Camp

I'll be presenting a session on "Determining when to use CLR in SQL" on Saturday, December 6, 2008 at the Tampa Code Camp event in Tampa, FL.  You can learn more about the event on their web site:

http://www.tampacodecamp.com/

Drop me a note if you will be attending so I can meet you.

Wednesday, November 26, 2008

The Database Transaction Log - Part 2: How the Transaction Log Works

The transaction log files are different from the database data files in the way that they are used, as well as how the space is allocated inside of them.  The Log files, unlike standard data files are written to sequentially.  For this reason, it is often best for the logs to be on dedicated disks for log use only.  Since the IO is all sequential, random I/O from the data files could impact performance of logging.  The log files are subdivided internally into Virtual Log Files as shown in the below picture from the Books Online:

VLF Division

The number of VLF's in the transaction log can be found using DBCC LOGINFO.  This is an undocumented command, but it provides some very useful information regarding the transaction log for a specific database.  The following image shows the output of DBCC LOGINFO for AdventureWorks on my laptop:

image_thumb[2]

As can be seen in the image, there are 4 VLF's in the transaction log.  The FSeqNo provides the logical order of the VLF's inside of the physical log files.  The Status column provides information as to whether a specific VLF is currently being used (2) or if it is available for use (0).  FileSize and offset provide information about the actual location of the VLF inside the physical file structure, and how large the VLF actually is. The actual sizing of the VLF is important to pay attention to.  If your VLF's are to small, then you will have excessive numbers of VLF's in your log files.  If they are to large, then they won't truncate free space effectively or efficiently. 

As mentioned previously, the transaction log is a sequentially written file that is used in a round robin fashion.  The start of the log file may not be the current start of the logical log.  The following image from the Books Online shows how a single log file with four virtual log files is used by the database server.

LogUsageSingleFile

The start of the logical log in this case is at the beginning of the third VLF.  Since the log is written sequentially, the log moves from the start of the third VLF through the fourth VLF and when it reaches the end of the file, starts back over at the beginning of the log file if there is free space.  So long as the end of the logical log never gets back to the start of the logical log, the transaction log will stay the same size.

In a two file system, the files are used sequentially, and unlike the database data files which are striped.  With two transaction log files, the first file is used, and then the second file is written to following the below picture:

TransactionLogMultiFileUsage

As long as the log space is truncated, the logs can continue to be used in a round robin fashion that prevents growth from being required.  The mechanism for truncation differs depending on the recovery model selected for the database in question.  If the database is in FULL recovery,  then the log is truncated when it is backed up using the BACKUP LOG command.  In SIMPLE recovery, the log truncation occurs on checkpoint for all complete transactions.  The active portion of the transaction log should remain fairly small for SIMPLE Recovery.  Exceptions to this would be large long running transactions as covered in my previous posting.

Saturday, November 22, 2008

PASS Summit 2008 Debriefing

I didn't blog much from PASS and it was intentional.  Since I was covering PASS sessions for Universal Thread, I didn't put time into covering them on here.  You can read about the sessions I attended on the following link:

http://www.utcoverage.com/PASS/2008

Reading about PASS Summit sessions will never match up to the experience of actually attending PASS Summit in person.  For me personally, the sessions were good, but the social networking us what really should drive people to attending events like PASS Summit.  I met and spoke with people from over a dozen different countries this week.  There were many MVP's at the summit which was simply awesome since I got to meet and hang out with the people who been teaching me SQL Server for the last 4 years.  I also got to sit on a discussion panel on Automating DBA Tasks, sponsored by Quest Software as a fill in for Buck Woody who was not able to make it at the last minute. 

If you'd like to catch up on PASS, check out the UT coverage above, but also check out the following blog post from Gail Shaw which lists some blogs to look at.  Also check out others that she missed:

drSQL (Louis Davidson)

If you aren't a member of PASS, I'd recommend that you join, it is after all free. 

Wednesday, November 19, 2008

Can a DBA function without rights to the Server OS?

I see posts often regarding questions for what rights should be granted and to whom with regards to SQL server.  On this post I am going to address what rights should a DBA have to the Server itself based on the following question recently from the MSDN Forums:

What is a DBA/sa prevented from doing if not a local admin on the SQL Server?

If you read the above post, you will see that my answer is different from start to finish on the thread.  At first I would have said that a DBA needs to be a Local Administrator on their server, but this really doesn't stand up to the whole idea of least necessary permissions, that as a DBA I enforce myself.  I happen to be a Local Administrator on my servers at my job, but that really probably is overkill, and could be reduced.  So what rights would a DBA need to a SQL Server at the OS level?

This is determined and or dictated by the definition of the role of a SQL Server DBA.  As a SQL Server DBA, there are certain things that I expect to be able to see and or do, and that I would argue belong within my realm of responsibility.  A short list of these tasks would be:

  1. Monitoring Performance Counters
  2. Managing Database Files
  3. Managing SQL Server Updates and Service Pack Installations
  4. Viewing System Event Logs
  5. View active Processes on the Server through PerfMon or TaskManager
  6. Start and Stop SQL Services
  7. Monitor Available Disk Space

Now arguably, the easiest way to accomplish the above is to make the DBA a member of the Local Administrators group on the SQL Server, and I would never argue against this practice, it is after all the DBA's job on the line if the server goes down from a mistake they made as a local administrator by goofing with something they shouldn't have.  I personally like having the rope to hang myself, but I can also use that same rope to climb out of a valley in the event of an emergency as well.  I personally know my limits, and I know when to involve my server team members with looking at a problem.  This may or may not be due to my past experience as an NT4 and Windows Server 2000 Administrator, it was something close to 8 years ago, but I know where to draw the line of responsibility.

So where do you sit on this subject?  I am interested to know if you are a DBA that doesn't have Administrator Access to the Windows Server, how you created permissions to do the above.  How would one go about granting the individual rights required to be a DBA without being a Local Administrator?  I can only figure out how to grant a subset of the above, but as I said previously, I am not a Windows Administrator, MCSE, or any other sort of subject matter expert when it comes to security outside of the SQL Server database engine itself.

Monday, November 17, 2008

Now on Twitter

A comment recently asked if I am on Twitter.  Well I wasn't but I am now.  Not sure what exactly I plan to do with it, but I can post short blurbs on what I am doing at the moment throughout the day I guess.

http://www.twitter.com/jmkehayias

I try to keep my online information business oriented and professional, so don't expect a whole lot of random rambling on there, but we'll see where it goes.  Not much room to do more than plug some small random stuff, perhaps using it to plug good posts on other peoples blogs rather than re-blogging it here......

Thursday, November 13, 2008

The Database Transaction Log - Part 1: Managing Size

This post will be the start of a series on the Database Transaction Log.  This started out as a single posting, but the topic is vast that there is no way to properly cover it in a single post.  I could probably write a mini pamphlet on the transaction log in SQL Server the topic is just that big.  I plan to focus on common problems that I consistently see on the MSDN Forums regarding the transaction log, as well as how to prevent/correct them.

The transaction log in SQL Server is one of the most important parts of a SQL Server database, as well as one of the most common generators of problems I see online.  If you don't believe me, do a Google, MSN, or Yahoo search for 'transaction log full', and you will find article after article and question after question dealing with the subject.  Worst yet are the stories of a deleted transaction log:

http://www.sqlservercentral.com/articles/Disaster+Recovery/63311/
https://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2727860&SiteID=1
http://bytes.com/forum/thread543465.html

To start with let me first say that you should never, ever, never, under any circumstances delete your database log file.  This is, as Jens Suessmeyer put it, "the transactional heart of the database." 

In a managed database server the database data/log files should only grow when specified by a Database Administrator.  This is not to say that you should turn AutoGrowth OFF on the databases in your environment.  I prefer that this option is left ON as a sort of insurance policy for your database in the event that the space available drops fast enough that you can't react in time to prevent a problem.  It should however, be configured to grow by a fixed size rather than a percentage.  The reason for this is that a fixed size has a predictable cost should the database have to grow automatically whereas a percentage size will be more and more expensive the larger the database grows to. 

I previously blogged about the How to Automate Common DBA Tasks series that I posted on the MSDN Forums Example Site.  One of the articles included in that series is a Data File Free Space monitoring script.  This can be used to monitor the available free space in the log files, and provide early notification to an administrator that they need to grow the file.  By manually managing the size of the log file, an administrator will know if there is a problem almost immediately.  The transaction log on an established database should very rarely have to be grown once properly sized.

So what exactly will cause the log file to fill up and need to be grown?  There are a number of things that can cause this:

  1. Full Recovery Model without Log Backups
  2. Long running transaction
  3. Uncommitted transaction
  4. Rebuilding Indexes
  5. Loading Bulk Data without minimizing logging.

The first item listed is the primary reason that log files get to be oversized, and eventually consume all of the available disk space on the server.  I have yet to figure out why or how, but almost every time that someone posts a problem with an oversized transaction log, the database is in FULL Recovery, and the only backups being performed are nightly full backups.  If you are not backing up the transaction log between full backups, then the database should be in SIMPLE recovery.  The reason for this is that the transaction log is not truncated in FULL recovery except by log backups using the BACKUP LOG command, and specifying WITH TRUNCATE_ONLY doesn't make sense.  If you aren't going to backup the logged data for point in time recovery purposes, then there is no reason to not have it auto truncate on checkpoint.

Long running transactions most often associated with a growing or oversized transaction log are generally data purging processes that are running as a single transaction like the following:

DELETE 
FROM MYTABLE
WHERE MYCOL
< @Criteria

Purging data like this will be heavily logged, even on databases in SIMPLE recovery.  The reason being that there is no commit between the start and commit, so if one million rows are being deleted, then the log has to hold all one million deletes to be able to perform a rollback of the operation.  The appropriate way to purge data like this was provided by fellow forum member Adam Haines in response to numerous forums postings:


DECLARE @BatchSize INT,
@Criteria DATETIME
SET
@BatchSize = 1000
SET @Criteria = '1/1/2005'

WHILE EXISTS(SELECT 1 FROM MYTABLE WHERE MYCOL < @Criteria)
BEGIN
DELETE TOP
(@BatchSize)
FROM MYTABLE
WHERE MYCOL < @Criteria
END

Another solution to this problem was provided by Denis the SQL Menace is:


DECLARE @BatchSize INT,
@Criteria
DATETIME,
@RowCount
INT
SET @BatchSize
= 1000
SET @Criteria = '20050101'
SET @RowCount = 1000

SET ROWCOUNT @BatchSize

WHILE @RowCount
> 0
BEGIN
DELETE
FROM MYTABLE
WHERE MYCOL
< @Criteria

SELECT @RowCount = @@rowcount
END

SET ROWCOUNT 0

Both of these solve the problem by working in smaller implicit transactions which will perform much better, as well as control the size of the transaction log. 


Uncommitted/Open transactions are problematic beyond just causing transaction log growth.  An open transaction will also cause excessive blocking in the database which will also impact the application users.  To find open transactions in a database, you can use DBCC OPENTRAN, which will return the active transactions in the current database.  To demonstrate this, run the following statement in one window:


use tempdb
go
create table mytable
(rowid int identity primary key)

begin transaction
insert into mytable default values

Then open a new window and run:


dbcc opentran

The output from DBCC OPENTRAN will show the open transaction and offending SPID in the database as follows:



Transaction information for database 'tempdb'.

Oldest active transaction:
    SPID (server process ID): 55
    UID (user ID) : -1
    Name          : user_transaction
    LSN           : (20:44:214)
    Start time    : Nov 13 2008 10:35:09:780PM
    SID           : 0x01050000000000051500000064116832e36ccd723422e75bba640000
DBCC execution completed. If DBCC printed error messages, contact your system administrator.


To investigate this further, you can use DBCC INPUTBUFFER(spid#) to get the last command run on the offending SPID.  From there, you can determine what action you want to take, whether to kill the offending SPID and cause it to rollback, or maybe troubleshoot further to identify what caused the transaction to be left open.


Rebuilding Indexes and bulk loading data should both be done in SIMPLE or BULK_LOGGED recovery.  The reason for this is to minimize the logging that is done, but you can't eliminate it completely.  In my experience, rebuilding indexes can require a transaction log to be larger than the size of your largest index.  This is where sizing your log file is important as a part of future capacity planning, and should be done considering how large the database might be in the future.


If you are reading this because you are already in trouble, there are a number of ways to deal with a oversized transaction log, and none of them necessitates deleting the file from the file system.  If you get yourself to the point that your server is completely out of disk space, there is no network path where you can backup your log to, and the log is in the hundreds of GB in size, then the best recommendation is to put the database into Simple recovery, which will truncate the active portion of the log and allow it to be shrunk.  I would highly caution and recommend that a new Full backup of your database be taken immediately after performing such an operation.


Look for further postings on the Transaction Log to come.


References:
http://support.microsoft.com/kb/873235
http://support.microsoft.com/kb/317375/

Monday, November 10, 2008

How do I become a SQL MVP?

I've been asked this both publicly and privately over the last month since I received the award, and I provided some information on a previous blog post Congratulations 2009 Microsoft MVP.  The real answer is that there isn't a magic formula that can be followed to become a MVP in any technology, let alone SQL Server.  The key requirement to becoming an MVP for any technology is a demonstrated dedication to supporting the community over the past year.  How one actually goes about supporting the community differs person to person and case by case. 

One thing to keep in mind is that quality is as important if not more important than quantity.  Posting responses to forums questions consistently but never actually answering the question at hand doesn't support the community very much.  Writing in a blog about personal information might build your blog post count, but it isn't centered towards a specific technology.  Being a member of a local user group and attending meetings but never presenting or being involved is good for personal learning, but not expanding the knowledge of the community. 

One of the requirements is that you have to be nominated by an existing MVP, or a staff member at Microsoft.  This entails that you have or are doing something that gets noticed like answering questions efficiently and effectively online, while providing information to explain and educate the requestor as well as anyone who may find the post by searching later on.  Speaking at local events and writing articles that get published in print or online are other ways to get noticed.  At least for SQL Server, many of the speakers at local events are current or former, yes I said former, MVP's.

So why did I say former?  The MVP award is only for one year, and if you stop contributing, you can be assured that you won't receive the award the following year.  Even if you do continue to contribute, it isn't guaranteed, see statement above about no magic recipe.  Each quarter the current MVP's whose award is expiring, and new candidates for MVP are reviewed by a team to determine who will receive the award.

Hopefully that answers the question for anyone who is curious, while not answering the question since there isn't a definitive answer to this question.  Personally the first email I got about being nominated caught me off guard.  I certainly don't count myself amongst the ranks of MVP's like Paul Randal, Kimberly Tripp, Kalen Delaney, or the long list of other subject matter experts whose work is well above anything I have done.

Friday, November 7, 2008

Are you safe without your Keys?

I am not talking about your house keys, or your car keys, I am talking about your SQL Server Keys.  SQL Server 2005 allows you to use keys for protecting objects and data in the server and databases.  It is very likely that if you are doing encryption in SQL Server that you already know that you have keys in SQL, but if you have never touched encryption, you might now know that, you too, have at least one key in SQL, the Service Master Key.  For those not familiar with this, the Service Master Key is the root of encryption key hierarchy in SQL Server 2005, it is by default used to encrypt Database Master Keys, linked server security information, and any credentials created using CREATE CREDENTIAL.  If you don't use any of the above, then read no further, you are probably fine.

Personally, I learned about keys, certificates, and encryption while studying for my MCITP Database Administrator exams at the beginning of this year, and that was enough to add a backup of the SMK into a password protected file to my installation procedures for each SQL Server Instance I have.  I personally have never needed to use the backup to date.  So what sparked this blog posting?  As usual, a post on the MSDN Forums, where a backup of a database using encryption was restored to a different server, and the poster didn't know the password to the database master key.  After goofing the initial answer on it, I had to do some investigating into what could be done in the case that the password to encrypt a DbMK is lost, and the answer isn't all that complex, and it is included in the post referenced above. 

However, it is much easier to just avoid the situation completely and have available backups of the SMK, as well as all the other keys in use in your database server. These can easily be done with DDL commands:

BACKUP SERVICE MASTER KEY (Transact-SQL)
RESTORE SERVICE MASTER KEY (Transact-SQL)

BACKUP MASTER KEY (Transact-SQL)
RESTORE MASTER KEY (Transact-SQL)

BACKUP CERTIFICATE (Transact-SQL)
CREATE CERTIFICATE (Transact-SQL)

One of the best references online is Laurentiu Cristophors blog on MSDN for security and cryptography in SQL Server.  Laurentiu is a frequent answerer in the SQL Security forum on MSDN, and has wealth of information available about this subject.  His blog is definitely a recommended read and is on my personal blog roll.

Since this is such a vast subject, I plan on putting some time into it in the near future, and writing some additional information on the subject.  However, in the mean time, backup those keys and certificates.

EDIT:  One thing I realized while thinking about his blog is I do have two different Certificates implemented in my servers, one for mirroring between two servers not on a domain, and one for a certificate user to provide permissions for a dynamic SQL search procedure that uses parameterized dynamic SQL to perform optimized searching in one of our databases, since application users are required to use stored procedures and have no table level access.  The certificate user has no associated login and is used WITH EXECUTE AS to provide the needed table level SELECT rights to run dynamic SQL code in the stored procedure.  The calling user only has execute rights on the stored procedure but can still make use of its dynamic code due to this type of impersonation.  I do have backups of both of these certificates, as created when they were created.

If you want more information about using Certificates to grant elevated rights with a Certificate User look at Erland Sommarskogs article Giving Permissions through Stored Procedures.

Thursday, November 6, 2008

Are your Disks Aligned Properly?

I am always on the lookout for new blogs to watch and learn from.  Not long ago, Kevin Kline wrote a very intriguing blog post:

How to Improve Application and Database Performance up to 40% in One Easy Step

I read it, but I didn't get a lot of time to dig into it until recently.  I finally got around to digging into the topic more, and I also spoke to one of our server admin's about it.  Doing some research we found that our entire environment is running on misaligned partitions.  I found an additional resource blog post that has an excellent slide deck on the MSDN blogs by a guy name Jimmy May:

Disk Partition Alignment (Sector Alignment) for SQL Server: Part 1: Slide Deck

I am working on doing some testing of this by rebuilding a disk completely to see how it affects SQLIO benchmarks before and after.  I'll post results later on, but this topic is definitely an interesting subject.

More to come........

Sunday, October 26, 2008

Tool Tip for Presenters

I made a personal note during Kendal Van Dykes presentation on XML in SQL Server to ask him what tool he was using to zoom in on his text during his demos yesterday at SQL Saturday.  I expected to find out about a tool that I would have to shell out a few dollars for, but instead Kendal was actually using a free tool from Microsoft SysInternals called ZoomIt.

After downloading this tool tonight to play with it, I feel it is definitely worthy of a blog posting.  I know that a few people who read my blog also do presentations on SQL Server for their local user groups as well as for larger events, and this tool in my opinion is simply amazing.  A lot of times, I try to remember to set my font sizes in Management Studio to at least 14 points or larger so that the text is readable on the projected screen.  Saturday morning however, I missed setting the results text to a larger size and the resulting 8 point font was impossible to read even standing at the podium in front of the room.  To fix this would have meant closing down Management Studio and restarting it, which would have put even more dead space in my presentation than I already had due to a few demonstrations that would not run. 

If you do any kind of public presentations, I highly recommend downloading this tool for use.  Many thanks to Kendal for letting me know about it after his session.