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.

Displaying Microsoft Project Task’s Notes in SSRS 2008

Lego Deadlock

I was asked to take a look at an issue the other day regarding displaying Microsoft Project Task’s Notes in SSRS 2008.  If you’ve worked with building reports for Microsoft Project Server, you have no doubt dealt with the RTF data that is stored in the Task’s Notes fields.

With SQL Server 2005 Reporting Services (SSRS) it was easy to display this information by following the steps outlined in Christophe Fiessinger post “How to display Microsoft Project Task’s Notes field in a report”.

But What About SSRS 2008

With SSRS 2008, the Reporting Services engine was re-architected.  Some of this new architecture included an improvement in the underlying security.  The question is did these changes have an effect the method available in the blog previously linked.

Unfortunately, it does.  Instead of displaying notes from Project Server as desired, you end up with row after row of N/A – as seen below.

image As a result, the code used for SSRS 2005 to display the RTF will not work with SSRS 2008.  Digging into the error message reveals that the reason that all of the tasks display as N/A is the following error message:

System.Security.SecurityException: Request for the permission of type ‘System.Security.Permissions.UIPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′ failed.
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessPermission.Demand()
at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Application.ParkHandle(CreateParams cp)
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.TextBoxBase.CreateHandle()
at System.Windows.Forms.RichTextBox.set_Rtf(String value)
at ReportExprHostImpl.CustomCodeProxy.byteArrayToString(Byte[] b)
The action that failed was:
Demand
The type of the first permission that failed was:
System.Security.Permissions.UIPermission
The Zone of the assembly that failed was:
MyComputer

No good.  The solution fails to function anymore because of the attempt to implement System.Windows.Forms.RichTextBox from within SSRS.  The new security restriction prevent this.

Can It Be Implemented Differently?

Investigating this more, I found an post on the Microsoft forums that dealt with issue.  In that post, there was a reference to a StackOverflow question that also was looking for a solution to this issue.

Both posts point towards adding the following function to the report:

Public Function ConvertRtfToTextRegex(ByVal input As String) As String
        Dim returnValue As String = String.Empty
        returnValue = System.Text.RegularExpressions.Regex.Replace(input, "\{\*?\\[^{}]+}|[{}]|\\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]?", "")
        Return returnValue
End Function

Instead of the code from the original Project Server post the code for the SSRS report should look like this:


'Instantiate a stringbuilder object
Public s As New System.Text.StringBuilder() 

Public Function byteArrayToString(ByVal b() As Byte) As String
    Dim i As Integer
    dim mystr as string 

Try
    s.length = 0 

    For i = 0 To b.Length - 1
        If i <> b.Length - 1 Then
            s.Append(chr(b(i)))
        End If
    Next 

    mystr = left(s.ToString, len(s.ToString)-1) 

    return ConvertRtfToTextRegex(mystr)
Catch ex as exception
    return ex.tostring()
    s.length = 0 

End Try
End Function 

Public Function ConvertRtfToTextRegex(ByVal input As String) As String
        Dim returnValue As String = String.Empty
        returnValue = System.Text.RegularExpressions.Regex.Replace(input, "\{\*?\\[^{}]+}|[{}]|\\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]?", "")
        Return returnValue
End Function

After adding the new code, the values that come back start looking as they would have with SSRS 2005.  Problem solved!

image

Follow-Up

While I’ve provided a solution to this issue, there is a little more to be garnered from this solution.  That is the power of the SQL Server community.  In solving this I didn’t have to have any inherent knowledge of UIPermissions and how they got hosed up because SSRS 2008 is more secure.  This is a good thing by the way. I also didn’t have to know how to write a goofy regular expression.  Thank God!

All I had to do was to take what I knew and start to search for items that were similar and follow where the trail led me.  In this way the common knowledge of the community was shared previously and I am sharing it again myself.

It’s a good thing to share what you know.  Whether through answering questions on forums, writing blog posts, or participating in your local SQL Server user groups.  This helps raise the bar for everyone else and expands the knowledge of our community.

SQL Server Best Practice Whitepapers

OMG

If you talk to Sarah (twitter), she’ll tell you that I like lists.  Lists are awesome – they are almost like non-structured data.  They are hierarchies of information that I can work with.  They are Data.

Microsoft must have known I liked lists because over the weekend I discovered (see below) their SQL Server Best Practice Whitepapers list.

If you are looking to shore up your environment and skills, this is the place to start.  Check it out – you’ll find some great stuff here.

UPDATE:

By discover above… I should have mentioned that I saw it on a post by Mark Broadbent (blog | twitter).  Attribution is always a good thing and I feel bad that I missed that one.

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.

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.

Connect Item on Import/Export Wizard

I like using raw files in SQL Server Integration Services (SSIS).  They are a quick way to build data repository that will be used else where in a package or for use with a separate package.  In a recent project, raw files were used to move client data around in a new import process that consolidated business logic and improved performance. 

As much as I like raw files, there is a place in SQL Server where the love I have for raw files is lacking.  This is with the Import/Export Wizard in Management Studio.  If you look through the wizard, you’ll find Excel love, Access love, and even some Oracle love.  But there isn’t an option to import or export raw file data.

 

Stop the Madness

Susan Powter said it best, “Stop the Madness”.  Ok, maybe this isn’t madness.  But it sure is irritating when I have to write an SSIS package from scratch to import a raw file to my sandbox database to see what data is in it that is causing issues.  If it were any other data source or destination, there wouldn’t be a need to do that extra work.

Is this extra work very hard?  No, of course not.  But this is a barrier to using this format.  I’ve been pushed away from them before when explaining the need to build a package to view raw file data.  When other formats can be imported with just a few clicks of a button.  The five to ten minutes to stop and build the package and import the data can add up in some situations.  And compating it to the minute or so to use the wizard, this can be a significant time savings when developing and testing SSIS packages.

There is certainly no sense in complaining without trying to fix.  So here it goes…

If you think this idea is kicking, special, or worthy of your support – please go out and vote up the Connect item that has been submitted on it.