Webcast Today – Using XML to Query Execution Plans

I’ll be speaking for the SQL PASS Database Administration Virtual Chapter today at 12 PM Eastern time.  The topic will be Using XML to Query Execution Plans.  The abstract for the event is the following:

SQL Server stores its execution plans as XML in dynamic management views. The execution plans are a gold mine of information. From the whether or not the execution plan will rely on parallelism to what columns are requiring a key lookup after a non-clustered index seek. Through a the use of XML this information can be available at your fingertips to help determine the value and impact of an index and guide you in improving the performance of your SQL Server databases. In this session we’ll look at how you can begin to understand and query the structure of the execution plans in the procedure cache. Also, we’ll review how to uncover some potential performance issues that may be lurking in your SQL Server.

You can get to the event here.

Webcast Next Week – Using XML to Query Execution Plans

I’ll be speaking for the SQL PASS Database Administration Virtual Chapter next week.  It’ll be on July 28 at 12 PM Eastern time.  The topic will be Using XML to Query Execution Plans.  The abstract for the event is the following:

SQL Server stores its execution plans as XML in dynamic management views. The execution plans are a gold mine of information. From the whether or not the execution plan will rely on parallelism to what columns are requiring a key lookup after a non-clustered index seek. Through a the use of XML this information can be available at your fingertips to help determine the value and impact of an index and guide you in improving the performance of your SQL Server databases. In this session we’ll look at how you can begin to understand and query the structure of the execution plans in the procedure cache. Also, we’ll review how to uncover some potential performance issues that may be lurking in your SQL Server.

If you register for the event ahead of time you will be entered into a drawing brought to us from CA, our event sponsor.  You can get to the event here.

Webcast Today – Performance Impacts Related to Different Function Types

I’ll be speaking for the SQL PASS Performance Virtual Chapter later today starting at 12 PM Eastern time.  The topic will be Performance Impacts Related to Different Function Types.  The abstract for the event is the following:

User defined functions provide a means to encapsulate business logic in the database tier.  Often the purpose of the encapsulation is to provide standard method access segments of data within the database.  Unfortunately, not all methods of creating user defined functions are equal.  In this session we’ll review the types of user defined functions and investigate the performance impact in selecting the different types

Goals:

  • Identify purposes for creating user defined functions
  • Discuss the types of user-defined functions
  • Demonstrate performance impact in selecting different types of functions

You can get to the event here.

Webcast Next Week – Performance Impacts Related to Different Function Types

I’ll be speaking for the SQL PASS Performance Virtual Chapter next week.  It’ll be on July 6 at 12 PM Eastern time.  The topic will be Performance Impacts Related to Different Function Types.  The abstract for the event is the following:

User defined functions provide a means to encapsulate business logic in the database tier.  Often the purpose of the encapsulation is to provide standard method access segments of data within the database.  Unfortunately, not all methods of creating user defined functions are equal.  In this session we’ll review the types of user defined functions and investigate the performance impact in selecting the different types

Goals:

  • Identify purposes for creating user defined functions
  • Discuss the types of user-defined functions
  • Demonstrate performance impact in selecting different types of functions

You can get to the event here.

Semaphore Timeout Did What?

Last week I had a blog about getting better error messages out of SQL Agent Jobs.  In that blog I had encountered the following error message:

Error: 2010-06-23 19:00:30.68
Code: 0×00000000
Source: Execute SQL Task
Description: TCP Provider: The semaphore timeout period has expired.
End Error

The downside is that I don’t have a good explanation for why this error occurred.  I talked to those that would investigate it and handed it off. 

The point for today is that after a lot of searching when this error came up, it turns out that there is a Microsoft KB article that is worth taking a look at when you encounter this error:

Advanced network adapter troubleshooting for Windows workstations

If you encounter this error, I wish you luck.  And hopefully you found the link I referenced faster than had I not put this out there.

Why’d That Job Fail?

Better than Bothan spiesHave you ever had a SQL Agent Job fail?  Of course, just like myself, you have had this happen.

When SQL Agent  jobs fail, you will want to know why it failed.  The problem is that knowing why a SQL Server Agent job has failed can sometimes be a tricky bit of business.

The typical issue I run into is that the output message on the job step is usually longer than the amount of space available to store the output message.  And as Murphey’s Law would predict, the bit of the message that contains the error will be at the tail end of the output message and not stored for later review.

Check Out The Message

Not exactly sure what I am talking about?  Take a look at the following failure message:

Executed as user AWESOMESTRATE ServiceAccount. …0.4035.00 for 32-bit Copyright (C) Microsoft Corp 1984-2005. All rights reserved. Started 63513 PM Error 2010-06-23 183536.87 Code 0xC001000E Source UserImport Description The connection SERVER_01 is not found. This error is thrown by Connections collection when the specific connection element is not found. End Error Error 2010-06-23 183536.87 Code 0xC001000E Source UserImport Description The connection SERVER_02 is not found. This error is thrown by Connections collection when the specific connection element is not found. End Error Error 2010-06-23 183536.88 Code 0xC001000E Source UserImport Description The connection SERVER_03 is not found. This error is thrown by Connections collection when the specific connection element is not found. End Error Error 2010-06-23 190030.68 Code 0×00000000 Source Log Import Activity Descript… The package execution fa… The step failed.

I got this a few weeks back on a SSIS package that was being executed.  The step had obviously failing based on the “The step failed.” message.  Why did it fail?  What didn’t happen?  Can you tell that the root cause of the error was based on an Execute SQL task?

Nope! You can’t and that’s the problem that prevents efficient troubleshooting of SQL Server Agent job issues.

Getting The Full Message

There should be a method for obtaining the full message so that you have what you need to troubleshoot job failures.  As there should be, there is.  This is available through on of the Advanced features on SQL Agent Job steps – the Output file.

image

If you set the Output file value to a path and file name, the output above will export the entire message generated by the SQL Server Agent job into a format that is much easier to read.

Below is the same job failure from above, but this time the output is from the Output file.  If you notice, without much trouble it is evident that the Execute SQL Task due to a TCP  Provider error.  Now instead of digging and looking around for the reason, the issue at hand can be resolved.

Microsoft (R) SQL Server Execute Package Utility
Version 9.00.4035.00 for 32-bit
Copyright (C) Microsoft Corp 1984-2005. All rights reserved.

Started:  6:35:13 PM
Error: 2010-06-23 18:35:36.87
Code: 0xC001000E
Source: UserImport
Description: The connection “SERVER_01″ is not found. This error is thrown by Connections collection when the specific connection element is not found.
End Error
Error: 2010-06-23 18:35:36.87
Code: 0xC001000E
Source: UserImport
Description: The connection “SERVER_02″ is not found. This error is thrown by Connections collection when the specific connection element is not found.
End Error
Error: 2010-06-23 18:35:36.88
Code: 0xC001000E
Source: UserImport
Description: The connection “SERVER_03″ is not found. This error is thrown by Connections collection when the specific connection element is not found.
End Error
Error: 2010-06-23 19:00:30.68
Code: 0×00000000
Source: Execute SQL Task
Description: TCP Provider: The semaphore timeout period has expired.
End Error
DTExec: The package execution returned DTSER_FAILURE (1).
Started:  6:35:13 PM
Finished: 7:01:05 PM
Elapsed:  1551.45 seconds

What About My Existing Job Steps?

At this point, hopefully I’ve got you convinced that a single tweak to your SQL Server Agent Job Steps can help you resolve failures with greater ease.  Let’s run out and update all of the SQL Servers and get this going.  No problem, right?

Well, what if your SQL Agent Job schedule has a few dozen jobs running.  Each job has a few steps.  And this is in an environment with a few dozen or hundred servers.  This can be a daunting task.  Daunting to the point that you just don’t have the time for this type of maintenance.

Fortunately, the script below can help you out by updating all of the job steps with a Output file details.  The script uses SQL Agent tokens to configure the job steps to output the files to the LOG folder under the SQL Server directory.  From there it assigns the Output file with the job name, the job step id, and the step name.  If you need to change directory location, just modify the @OutputFileDir variable.


DECLARE @OutputFileDir varchar(128)
SET @OutputFileDir = '$(ESCAPE_SQUOTE(SQLDIR))\LOG\'

SELECT
'EXEC msdb.dbo.sp_update_jobstep @job_id=N''' + CONVERT(varchar(36), j.job_id)
+ ''', @step_id=' + CONVERT(varchar(3), js.step_id)
+ ',@output_file_name=N''' + @OutputFileDir
+ REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(j.name,SPACE(1)
, '_'),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')
+ '_$(ESCAPE_SQUOTE(STEPID))_'
+ REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(js.step_name,SPACE(1)
, '_'),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','') + '.txt''
GO'
FROM dbo.sysjobsteps js
INNER JOIN dbo.sysjobs j ON j.job_id = js.job_id
WHERE enabled = 1

Sweet, Run This In Production

No, please don’t do that… yet.

If you like this, check it out in your development environment and make certain that it works for you.  Then go ahead with your regular application lifecycle to promote this to other environments.  Who knows, HTML encoding might break part of this script and cause issues – it happened on a post of mine last week.

Do You Patch SQL Server Regularily?

Lego DeadlockMicrosoft has released a few new Cumulaive Update for SQL Server. There is an update for each of the supported releases of SQL Server:

Cumulative Updates are primarily intended for SQL Server environments where the issues being resovled are being realized. Though if you are using the components updated by the Cumulative Update it would be good to apply the update.

Unless, of course, you’d rather spend the weekend behind an 8-Ball troubleshooting and resolving an issue that the Cumulative Update would have prevented. The 8-Ball might be a black and blue ball by Monday when you explain to your manager that the issue was completely avoidable.

Patch Regularily

If you aren’t aware, Microsoft has an Incremental Servicing Model. This model provides guidance on what you should expect from Microsoft from a support standpoint for issues with their products. As part of the Incremental Servicing Model, Microsoft is committed to releasing Cumulative Updates every 2 months.

All fine and dandy but what does that have to do with you? Or if today still feels like Monday… So what?

The benefit of this model is that it allows us as administrators of SQL Server to develop a plan to regularily download and install the updates. This plan would, of course, include a process to install the updates in the development and test environments. And, also, detail what the steps are for testing and releasing these updates.

But That’s Not All

Just like practicing your database recovery plan. You do practice this, right? Regularily updating your SQL Server environment provides an opportunity to become familiar with this task. This is a critical skill that every DBA should want to have.

If you are well versed in a simple Cumulative Update deployment you have skill and knowledge that will be critical in other situations. When a hotfix needs to be deployed, you will already know your systems well enough to understand the collateral impact of the deployment. If you suddenly inherit a SQL Serve that hasn’t been maintained since an RTM install, you know what level of patching to place on the server and already have a process in place to get the job done.

Regular updates of your SQL Server environment also gives you the opportunity to read the Cumulative Update notes. You will know what wasn’t working and become an expert on problems that may exist in your environment. I’d rather say, “There is a fix to that issue already in progress. It’s in the Test environment already.” Than have to come back and say, “Microsoft fixed that in an update 6 months ago, I’ll see what we need to do to get the update deployed.”

There are likey countless other reasons to take the time to build a process and skillset around regular patching. The long and the short of it is that it is good for you, good for your company, and the responsible thing to do.

Index Those Foreign Keys

Lego DeadlockToday started with some quality time getting to know a deadlock that had occurred. While working through the deadlock, I noticed that there were a number of foreign key relationships that weren’t indexed on the parent side of the relationship.

I am going to skip over the why to index foreign keys and save that for a later point when I have more time to go through it with some really pretty pictures. Today though, I want to share the scripts that I put together to look for these situations and help prevent issues related to them.

Brute Force Indexing

This first script is a brute force attack on this need. If you set the output for text results in SQL Server Management Studio (SSMS) you’ll get a script with all of the indexes you’ll need to cover all of your foreign key relationships.


SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON

;WITH cIndexes
AS (
SELECT i.object_id
,i.name
,(SELECT QUOTENAME(ic.column_id,'(')
FROM sys.index_columns ic
WHERE i.object_id = ic.object_id
AND i.index_id = ic.index_id
AND is_included_column = 0
ORDER BY key_ordinal ASC
FOR XML PATH('')) AS indexed_compare
FROM sys.indexes i
), cForeignKeys
AS (
SELECT fk.name AS foreign_key_name
,'PARENT' as foreign_key_type
,fkc.parent_object_id AS object_id
,STUFF((SELECT ', ' + QUOTENAME(c.name)
FROM sys.foreign_key_columns ifkc
INNER JOIN sys.columns c ON ifkc.parent_object_id = c.object_id AND ifkc.parent_column_id = c.column_id
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')), 1, 2, '') AS fk_columns
,(SELECT QUOTENAME(ifkc.parent_column_id,'(')
FROM sys.foreign_key_columns ifkc
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')) AS fk_columns_compare
FROM sys.foreign_keys fk
INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
WHERE fkc.constraint_column_id = 1
UNION ALL
SELECT fk.name AS foreign_key_name
,'REFERENCED' as foreign_key_type
,fkc.referenced_object_id AS object_id
,STUFF((SELECT ', ' + QUOTENAME(c.name)
FROM sys.foreign_key_columns ifkc
INNER JOIN sys.columns c ON ifkc.referenced_object_id = c.object_id AND ifkc.referenced_column_id = c.column_id
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')), 1, 2, '') AS fk_columns
,(SELECT QUOTENAME(ifkc.referenced_column_id,'(')
FROM sys.foreign_key_columns ifkc
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')) AS fk_columns_compare
FROM sys.foreign_keys fk
INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
WHERE fkc.constraint_column_id = 1
), cRowCount
AS (
SELECT object_id
,SUM(row_count) AS row_count
FROM sys.dm_db_partition_stats ps
WHERE index_id IN (1,0)
GROUP BY object_id
)
SELECT
'--Missing foreign key index for '+fk.foreign_key_name+CHAR(13)+CHAR(10)+'GO'+CHAR(13)+CHAR(10)+
+'CREATE NONCLUSTERED INDEX FKIX_'+OBJECT_NAME(fk.object_id)+'_'+REPLACE(REPLACE(REPLACE(REPLACE(fk.fk_columns,',',''),'[',''),']',''),' ','')
+CHAR(13)+CHAR(10)+
+'ON [dbo].['+OBJECT_NAME(fk.object_id)+'] ('+fk.fk_columns+')'+CHAR(13)+CHAR(10)+
+'GO'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)
FROM cForeignKeys fk
INNER JOIN cRowCount rc ON fk.object_id = rc.object_id
LEFT OUTER JOIN cIndexes i ON fk.object_id = i.object_id AND i.indexed_compare LIKE fk.fk_columns_compare + '%'
WHERE i.name IS NULL
ORDER BY OBJECT_NAME(fk.object_id), fk.fk_columns

Foreign Key Monitoring

This second script accommodates for those situations when you may not want to just index every foreign key that is out there. Maybe there’s a really old table in the database with a foreign key relationship that just doesn’t matter any more. Is it worth indexing along a vector that won’t lead to any performance impact – either negative or positive? Most likely not.

For this script, the results output a list of foreign keys relationships that are not fully indexed. Included in the result script is a column with XML data in it that contains a script for creating an index. You may notice that the format for this is very similar to the schema created when outputtingmmissing Indexes from execution plans.


SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

;WITH cIndexes
AS (
SELECT i.object_id
,i.name
,(SELECT QUOTENAME(ic.column_id,'(')
FROM sys.index_columns ic
WHERE i.object_id = ic.object_id
AND i.index_id = ic.index_id
AND is_included_column = 0
ORDER BY key_ordinal ASC
FOR XML PATH('')) AS indexed_compare
FROM sys.indexes i
), cForeignKeys
AS (
SELECT fk.name AS foreign_key_name
,'PARENT' as foreign_key_type
,fkc.parent_object_id AS object_id
,STUFF((SELECT ', ' + QUOTENAME(c.name)
FROM sys.foreign_key_columns ifkc
INNER JOIN sys.columns c ON ifkc.parent_object_id = c.object_id AND ifkc.parent_column_id = c.column_id
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')), 1, 2, '') AS fk_columns
,(SELECT QUOTENAME(ifkc.parent_column_id,'(')
FROM sys.foreign_key_columns ifkc
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')) AS fk_columns_compare
FROM sys.foreign_keys fk
INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
WHERE fkc.constraint_column_id = 1
UNION ALL
SELECT fk.name AS foreign_key_name
,'REFERENCED' as foreign_key_type
,fkc.referenced_object_id AS object_id
,STUFF((SELECT ', ' + QUOTENAME(c.name)
FROM sys.foreign_key_columns ifkc
INNER JOIN sys.columns c ON ifkc.referenced_object_id = c.object_id AND ifkc.referenced_column_id = c.column_id
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')), 1, 2, '') AS fk_columns
,(SELECT QUOTENAME(ifkc.referenced_column_id,'(')
FROM sys.foreign_key_columns ifkc
WHERE fk.object_id = ifkc.constraint_object_id
ORDER BY ifkc.constraint_column_id
FOR XML PATH('')) AS fk_columns_compare
FROM sys.foreign_keys fk
INNER JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
WHERE fkc.constraint_column_id = 1
), cRowCount
AS (
SELECT object_id
,SUM(row_count) AS row_count
FROM sys.dm_db_partition_stats ps
WHERE index_id IN (1,0)
GROUP BY object_id
)
SELECT
fk.foreign_key_name
,OBJECT_NAME(fk.object_id) AS fk_table_name
,fk.fk_columns
,rc.row_count AS row_count
,CAST('<!--dex  '+CHAR(13)+CHAR(10)+'Missing foreign key index for '+fk.foreign_key_name+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)+'USE ['+DB_NAME()+']'<br--> +CHAR(13)+CHAR(10)+'GO'+CHAR(13)+CHAR(10)+
+'CREATE NONCLUSTERED INDEX []'+CHAR(13)+CHAR(10)+
+'ON [dbo].['+OBJECT_NAME(fk.object_id)+'] ('+fk.fk_columns+')'+CHAR(13)+CHAR(10)+
+'GO'+CHAR(13)+CHAR(10)+'--?>' AS xml) foreign_key_index_schema
FROM cForeignKeys fk
INNER JOIN cRowCount rc ON fk.object_id = rc.object_id
LEFT OUTER JOIN cIndexes i ON fk.object_id = i.object_id AND i.indexed_compare LIKE fk.fk_columns_compare + '%'
WHERE i.name IS NULL
ORDER BY OBJECT_NAME(fk.object_id), fk.fk_columns

Closing Up

The DDL schema output in these scripts is very basic. It doesn’t account for potentially important things like partitions and filegroups. Obviously, you’ll need to modify this for your own environment and don’t just run this on production.

I see a lot of potential in these scripts and am planning to include them as part of preparing for releases when I am clients. A good way to dot the i’s and cross the t’s.

Individual results may vary. No Legos were harmed in the writing on this post.

Doing Something About Auto Generated Names

Zombie Apocafest 2009 - Shaun & EdI like my name.  It provides a point of reference to who I am.  If I am at work and someone calls for “Jason Strate”… that’s me.  If I am at home, the same thing can happen and I still know that it’s me.  I know that no matter where I am, my name will be a constant and it means something when it is called.  Hopefully, it doesn’t mean “late to dinner”.

This same principle applies to the tables and the objects related to those tables.  We give that table a name in the development environment, maybe it’s called “ZombieBaconUnicorn”.  We expect that it will be called “ZombieBaconUnicorn”.  Unfortunately, this doesn’t always ring true with other database objects related to tables; such as Primary Keys and Defaults Constraints.

Random Naming

There are multiple ways to create Primary Key and Default Constraints and they don’t all have an implied name.  Take for instance the following script, what would you assume the names of the Primary Key and Default Constraints would be?

CREATE TABLE dbo.RandomPKandDC
(
RandomPKandDCID int IDENTITY(1,1) PRIMARY KEY CLUSTERED
,Column1 datetime DEFAULT(GETDATE())
)

SELECT name FROM sys.objects
WHERE parent_object_id = OBJECT_ID('dbo.RandomPKandDC')

Did you guess the following names?

image

No?!  Run it on you machine, you’ll get your own unique names.

Non-Random Naming

Getting around the random naming is pretty simple.  Below I’ll would you through the steps.

The first change is how you’ll define the PRIMARY KEY on the table with the CREATE TABLE statement.  Instead of adding PRIMARY KEY CLUSTERED on the column definition, add it to the table as a constraint.

CREATE TABLE dbo.NonRandomPKandDC
(
NonRandomPKandDCID int IDENTITY(1,1)
,Column1 datetime
,CONSTRAINT PK_NonRandomPKandDC_RandomPKandDCID PRIMARY KEY CLUSTERED (NonRandomPKandDCID)
)

Next you want to use the ALTER TABLE statement to add the DEFAULT CONSTRAINT.  Instead of making the default part of the column definition in the CREATE TABLE, you want to name the default as a constraint to name it as it is created.

ALTER TABLE dbo.NonRandomPKandDC ADD CONSTRAINT DF_NonRandomPKandDC_Column1
DEFAULT (getdate()) FOR [Column1]

Take a look at the results of the next query:

SELECT name FROM sys.objects
WHERE parent_object_id = OBJECT_ID('dbo.NonRandomPKandDC')

image

On your server and mine the objects will have the same name.  When you deploy objects build from T-SQL like this from development to test to production they will have the same names.

What the!?

Now there isn’t anything wrong with these random names from the perspective of how your database will perform.  But it will hose up things such as database comparisons and investigating errors.

With database comparisons, the issue is pretty obvious.  If the contents of the object are the same but the name is different then it isn’t the exact same object.  Many tools have options for ignoring these names, but there are some that don’t.  Even when the tool has the option to ignore, you will need to rely on the operator of the tool to disable the feature.

Looking now at investigating errors, I am a big fan of errors that can tell me the problem within the database.  Which of the following is easier to understand.  The first with the random name:

Msg 2627, Level 14, State 1, Line 2
Violation of PRIMARY KEY constraint ‘PK__RandomPKandDC__5D60DB10′. Cannot insert duplicate key in object ‘dbo.RandomPKandDC’.
The statement has been terminated.

Or the second with the stated name:

Msg 2627, Level 14, State 1, Line 2
Violation of PRIMARY KEY constraint ‘PK_NonRandomPKandDC_RandomPKandDCID’. Cannot insert duplicate key in object ‘dbo.NonRandomPKandDC’.
The statement has been terminated.

Ok, maybe this isn’t the best example of this type of issue, but it does tell me exactly the issue and because I named the object explicitly I know where the problem is and something about the issue before digging into the schema of the table.

Overall, this is about reducing pain points in building and using your databases.  The easier it is to manage them once they are deployed, the more Bejeweled Blitz you can play on Facebook between your projects.

Renaming the Objects

Maybe I’ve sold you on this idea.  If so, you may be thinking “What the heck do you do with all of my existing databases objects?”  That answer is simple… rename them.  Since the names of these objects isn’t tied to how they are defined, you can easily get them renamed with sp_rename.

The following two scripts are what I use to rename PRIMARY KEY CONSTRAINTS and DEFAULT CONSTRAINTS.

This first one will provide sp_rename statements that you can execute to rename all of your PRIMARY KEY CONSTRAINTS:

;WITH PKNames
AS (
SELECT name AS IndexName
,OBJECT_NAME(object_id) AS TableName
,OBJECT_SCHEMA_NAME(object_id) as SchemaName
,(SELECT '' + c.name
FROM sys.index_columns ic
INNER JOIN sys.columns c
ON ic.object_id = c.object_id
AND ic.index_column_id = c.column_id
WHERE ic.object_id = i.object_id
AND ic.index_id = i.index_id
AND ic.is_included_column = 0
ORDER BY ic.key_ordinal
FOR XML PATH('')) AS Columns
FROM sys.indexes i
WHERE i.is_primary_key = 1
)
SELECT 'EXEC sp_rename ''' + QUOTENAME(SchemaName) + '.' + QUOTENAME(IndexName) + ''', ''PK_' + TableName + '_' + Columns + ''''
FROM PKNames
WHERE IndexName <> 'PK_' + TableName + '_' + Columns

The second one will provide sp_rename statements that you can execute to rename all of your DEFAULT CONSTRAINTS:

SELECT 'EXEC sp_rename ''' + QUOTENAME(OBJECT_SCHEMA_NAME(dc.parent_object_id)) + '.'
+ QUOTENAME(dc.name) + ''', ''DF_' + OBJECT_NAME(dc.parent_object_id) + '_' + c.name + ''''
FROM sys.default_constraints dc
INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND dc.parent_column_id = c.column_id
WHERE dc.name <> 'DF_' + OBJECT_NAME(dc.parent_object_id) + '_' + c.name

Hopefully these can be helpful for you as well.

Conclusion

In a roundabout way, this post has been about naming conventions.  Make the world a prettier place by having a convention on naming the objects in your database.

Last word… don’t just run out and use this in your production database without doing your own testing and promoting using your own company’s deployment process.  An obvious statement but one that I thought I should point out since I know how tempting this can be.

EDIT 2010/05/27: Modified scripts to account for schema variations.

TechFuse Presentation and Speaker Rankings

Last week I spoke at TechFuse 2010 and my topic was Getting to Know Your Indexes.  I thought I’d throw up a link to the presentation materials from the event.  TechFuse was a lot of fun and I got to spend some time chatting with Dan English (twitter | blog) and Lara Rubbelke (twitter | blog) about SQL Server 2008 R2.

From my session, I received some feedback and it came back a lot better than I had expected.  I hadn’t felt on my game that day and this presentation is usually pretty dry compared to others that I do.  On a scale of 1-7 I received the following scores:

  • 6.6 – Speaker(s) demonstrated expertise on the subject matter
  • 5.7 – Knowledge in this session will help me in the job role
  • 5.4 – Content delivered met my expectations
  • 5.6 – I enjoyed the subject matter

Some of the comments I received…

“A lot of useful information.”
“Good Info.”
“Lots of detail. Speaker very knowledgeable.”

If you saw me there and want to drop an additional comment, feel free to add a comment at SpeakerRate.

Also, if you saw me present on Application and Multi-Server Management at the SQL Server 2008 R2 launch event in Minneapolis I’d appreciate any feedback on that as well.