Welcome to MSDN Blogs Sign in | Join | Help

Best Practice: Naming Constraints

Within SQL Server there are a number of different types of constraints:

  • CHECK
  • DEFAULT
  • FOREIGN KEY
  • PRIMARY KEY
  • UNIQUE

The reference for CREATE TABLE can be found here.

Now what’s interesting about constraints is when creating a constraint the name is optional. If you don’t provide a name the system will provide one for you. This is sort of like if you cannot afford an attorney one will be provided by the court. The syntax for DEFAULT looks like this:

[ CONSTRAINT constraint_name ] DEFAULT constant_expression

The ‘[‘ ‘]’ around “CONSTRAINT constrain_name” mean the statement is optional.

It’s very nice of the system to provide the constraint name on your behalf but just like anyone in their right mind would hire their own lawyer – assuming they can afford it, etc – any developer in their right mind should provide their own constraint name. Why you ask. The answer is obvious, the constraint is part of your application and since the system provides control over the name you should exercise that right.

The syntax to name a constraint is simple and only requires two additional entries over the syntax for system generated names. Said another way, don’t give me the lazy excuse that allowing the system to name your constraints saves you time. In fact, this might become part of my standard arsenal of DBA interview questions: do you name your constraints? Or something like that.

Let’s take a closer look at the differences. Just for fun I’ll use a DEFAULT constraint in my example.

System Named Constraint

CREATE TABLE dbo.SystemNamedConstraint ( column1 INT DEFAULT 42 )

The result of the above will differ between systems but in my case I ended up with a constraint on the table named: DF_SystemNam_colum_07020F21. Not overly friendly.

Programmer Named Constraint

CREATE TABLE dbo.ProgrammerNamedConstraint ( column1 INT CONSTRAINT DF_column1 DEFAULT 42 )

The result of the above won’t differ between systems and as you expect you’ll end up with a constraint on the table named: DF_column1.

You’ll notice I used DF as the prefix on my constraint name. Mainstream abbreviations include:

  • CHECK: CK
  • DEFAULT: DF
  • FOREIGN KEY: FK
  • PRIMARY KEY: PK
  • UNIQUE: UQ

There are variants to these for things like CLUSTERED (CL or in the case of a PRIMARY KEY – PKCL). But there’s no reason you couldn’t come up with your own standard.

The bottom line is don’t be a lazy DBA/Programmer and let the system name your constraints. The few extra taps on the keyboard will be worth it in the long run.

Posted by dtjones | 0 Comments
Filed under:

Developing Data-tier Applications Using Visual Studio 2010

Check out this rocking video of Sanjay Nagamangalam demoing the Data-tier Application functionality within Visual Studio 2010. Sanjay is a GPM on the SQL Server team. Sanjay has sessions at SQL PASS and PDC.

PDC Session on the Data-tier Application Component

Are you going to this year’s PDC? Are you still on the fence? There’s a very cool session @ PDC on the data-tier application component called “Simplifying Application Packaging and Deployment with SQL Server 2008 R2”. Yes, that’s probably one of the longest session titles ever. Omri Bahat, a PM on my team, recently sat down with Robert Hess (The Knowledge Chamber) to discuss the DAC and the session @ PDC. You can view the video here. Even if you’re not attending PDC you should watch the video to learn more about this fantabulous new technology in SQL Server 2008 R2 and Visual Studio 2010.

Perfect Conference Storm

November is shaping up to be the perfect storm of conferences. In a time when budgets are extremely tight it amazes me that we have 4 conferences to cover in November.

 

  1. SQL PASS
    1. When: November 2-5, 2009
    2. Where: Seattle, Washington
    3. Site: http://summit2009.sqlpass.org/
    4. Sessions: 2 focused on SQL Server 2008 R2/Visual Studio 2010
  2. SQL Connections
    1. When: November 9-12, 2009
    2. Where: Las Vegas, Nevada
    3. Site: http://www.devconnections.com/shows/FALL2009SQL
    4. Sessions: 3 – 1 on SQL Server 2008 R2/Visual Studio 2010 and 2 on SQL Server 2008
  3. TechEd Europe
    1. When: November 9-13, 2009
    2. Where: Berlin, Germany
    3. Site: http://www.microsoft.com/europe/teched/
    4. Sessions: 3 – 1 on SQL Server 2008 R2/Visual Studio 2010 and 2 on SQL Server 2008
  4. PDC
    1. When: November 17-19, 2009
    2. Where: Los Angeles, California
    3. Site: http://microsoftpdc.com/
    4. Sessions: 1 focused on SQL Server 2008 R2/Visual Studio 2010

We have a tremendous amount of great content @ each of these conferences.

 

It’s been a while since I’ve presented so I’m seriously considering taking the SQL Connections gig. After all I love Vegas and my brother from another mother and SQL Server MVP Steve Jones will be there. What more could I ask for.

PBM – it’s like liquid awesome!

Brent Ozar and Thomas LaRock do a 3 part video series on the power of Policy-based Management (PBM). Interestingly SCOM comes up several times in the discussion.

 

They cover the basics of PBM and Thomas goes into more depth on how he’s using it in his environment. The series is about 35 minutes in total.

 

Regardless of your PBM experience level I highly recommend watching these videos.

 

http://thomaslarock.com/2009/08/policy-based-management-podcast-part-1/

http://thomaslarock.com/2009/08/policy-based-management-podcast-part-2/

http://thomaslarock.com/2009/08/policy-based-management-podcast-part-3/

SQL Server 2008 R2 August CTP: Utility Bug

The August CTP of SQL Server 2008 R2 contains a bug in Management Studio when connected to a Control Point. You can find the details here: http://social.msdn.microsoft.com/Forums/en-US/sqlkjappmsmgmt/thread/03506a9b-e9b1-4d77-a3e1-28627e8f4867

SQL Server Web Developer Survey

The Microsoft SQL Server product team is undertaking a short survey to help guide potential new features and capabilities for web developers, please take a few minutes to take the survey and help shape the future of SQL Server. The survey will run for about a week (closing on 6/17 or there about) so don’t delay.

http://www.surveymonkey.com/s.aspx?sm=9s5sHwoJ97OV0OWt60idJA_3d_3d

 

I promise the survey is short – only 7 questions!

Posted by dtjones | 0 Comments
Filed under:

PCI Compliance and SQL Server 2008

Today compliance is a huge focus area for IT. Since compliance is written by lawyers for lawyers it takes a fair amount of translation to get it to the point where IT can understand what processes, policies, and configuration to implement to meet the requirements for a given compliance spec.

If you are a SQL Server DBA and face PCI compliance this white paper is a must read and the accompanying TechNet webcast a much watch.

Posted by dtjones | 1 Comments
Filed under: ,

Using PowerShell to Get Data & Log File Sizes

I was playing around with PowerShell today (yes I’m was geeking out on Saturday afternoon) to learn how to access Performance Counters using PowerShell. My mission was to write a script that would return the Data File and Log File sizes for each database and a total for the instance. The good news is SQL Server already provides a bunch of fun performance counters and PowerShell has built-in support for accessing performance counters. I thought this was pretty cool so I decided to share it. In addition, I hadn’t blogged in a while and I was feeling bad about that.

There are two groups of scripts and sample output below: 1) Data File Space and 2) Log File Space.

Sorry about the formatting of the output I’m just being lazy today – after all it is Saturday.

Have fun with it!

Oh, btw: I was doing this on a Win7 machine (which I also need to give an update on) so I had to launch PS as administrator so it had access to the perf counters (same should be true on Vista and Windows Server 2K8). If you don’t launch as admin you’ll get an error that looks like this:

Get-Counter : The specified instance is not present.
At line:1 char:26
+ $DBDataFile = Get-Counter <<<<  -Counter '\MSSQL$SQL2K8_01:Databases(*)\Data File(s) Size (KB)' -MaxSamples 1
    + CategoryInfo          : InvalidResult: (:) [Get-Counter], Exception
    + FullyQualifiedErrorId : CounterApiError,Microsoft.PowerShell.Commands.GetCounterCommand

 

Data File Space

#Displays the total Data File size for each database (including system databases)

$DBDataFile = Get-Counter -Counter '\MSSQL$SQL2K8_01:Databases(*)\Data File(s) Size (KB)' -MaxSamples 1

$DBDataFile.CounterSamples | where-object -FilterScript {($_.InstanceName -ne "_total")} | sort-object -Property InstanceName | format-table @{Label = "Database"; Expression={$_.InstanceName}}, @{Label = "Total Data File(s) Size (MB)"; Express={$_.CookedValue/1000}} -AutoSize

Database Total Data File(s) Size (MB)

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

ansicheck 2.304

master 4.096

model 1.28

msdb 10.752

mssqlsystemresource 61.696

pbm-prototype 2.048

tempdb 8.192

 

We can also just grab the total Data File space used by the instance:

$DBDataFile = Get-Counter -Counter '\MSSQL$SQL2K8_01:Databases(*)\Data File(s) Size (KB)' -MaxSamples 1

$DBDataFile.CounterSamples | where-object -FilterScript {($_.InstanceName -eq "_total")} | sort-object -Property InstanceName | format-table @{Label = "Database"; Expression={$_.InstanceName}}, @{Label = "Total Data File(s) Size (MB)"; Express={$_.CookedValue/1000}} -AutoSize

Database Total Data File(s) Size (MB)

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

_total 90.368

 

Log File Space

#Displays the total Log File size for each database (including system databases)

$DBLogFile = Get-Counter -Counter '\MSSQL$SQL2K8_01:Databases(*)\Log File(s) Size (KB)' -MaxSamples 1

$DBLogFile.CounterSamples | where-object -FilterScript {($_.InstanceName -ne "_total")} | sort-object -Property InstanceName | format-table @{Label = "Database"; Expression={$_.InstanceName}}, @{Label = "Total Log File(s) Size (MB)"; Express={$_.CookedValue/1000}} -AutoSize

Database Total Log File(s) Size (MB)

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

ansicheck 0.496

master    1.016

model 0.504

msdb 0.504

mssqlsystemresource 0.504

pbm-prototype 1.016

tempdb 0.504

 

We can also just grab the total Log File space used by the instance:

$DBLogFile = Get-Counter -Counter '\MSSQL$SQL2K8_01:Databases(*)\Log File(s) Size (KB)' -MaxSamples 1

$DBLogFile.CounterSamples | where-object -FilterScript {($_.InstanceName -eq "_total")} | sort-object -Property InstanceName | format-table @{Label = "Database"; Expression={$_.InstanceName}}, @{Label = "Total Log File(s) Size (MB)"; Express={$_.CookedValue/1000}} –AutoSize

Database Total Log File(s) Size (MB)

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

_total 4.544

Up & Running on Win7

Rock and Roll! Yesterday I did a clean install of Win7 x64 Beta on my Lenovo x301. Setup was fast and completed without any issues. In fact it had no problem with the SATA drive set in AHCI mode. The Vista RTM install couldn’t handle that. I had to use a custom driver or switch it in to compatibility mode.

Boot time is lightening fast as is resume from sleep. I haven’t played much with hibernate yet. Yes this is a clean OS install but I did a clean install of Vista on the same machine recently and it was not nearly as fast.

Over all performance feels much zippier. Apps load more quickly and the system feels far more responsive.

So far I’ve only run into three minor issues:

1) The current release of Live Mesh doesn’t play nicely with Vista video settings. I got a dog food QFE from the Mesh team that cleared the issue up. I don’t know when this will be released publically. (note: Dog Food is an internal term used for testing another groups product prior to public release.)

2) For some reason Win 7 didn’t play nicely with the sound system. I cleared this up by repairing the driver install. The build of Win 7 I installed is an Microsoft IT (MSIT) build. They mock with a bunch of stuff so I don’t know if I can blame this on Win 7 or not.

3) The start menu froze on me just once. It happened in a strange situation. Again this could have been caused by some Microsoft IT (MSIT) stuff.

So for all of my road testing in the last day I can safely say I’m impressed. I haven’t played with many of the new features yet. Once I do I’ll report back.

Now for the early litmus test – do I want to go back to Vista? So far the answer is no.

Posted by dtjones | 1 Comments
Filed under: ,

What Has 2 Thumbs & Is Excited About Windows 7?

Answer: This guy!

I’ve been following very closely the press and reviews on the early peaks of Windows 7. I’m not as big of a Vista hater as some people out there. In fact I like the OS. I recently had to reinstall XP on another machine and was absolutely astonished how old it looked and felt. In fact I couldn’t stand it, I had to reinstall Vista on the machine right away.

Being a MS employee and shareholder I have double the interest in Windows 7 being successful. But I’m also a critic. I look at each of our products with a scrutinizing eye. If you read my blog you’ll find two MS products that I absolutely love: Windows Live Writer (which I use to write this blog) and Windows Live Mesh (which I use to synchronize files between machines). I’m also a huge fan of SQL Server (duh!) But I am a critic of the product and I know first hand it’s not perfect, especially in the manageability space, but I’m working tirelessly to improve it one release at a time.

Back to Windows 7. Part of me felt that Windows 7 wouldn’t have a chance of being successful. Granted it would almost be impossible to cause a worse impression than Vista but I felt people would hold it to an unfairly high bar and nit pick every last square inch. Everything I’ve read thus far is very favorable. On top of that there seems to be some excitement for it!

One of my very good friends did a clean install and an upgrade from Vista without a hitch. He’s super critical and even he had great things to say: GUI enhancements, power management enhancements, etc.

I’m starting to believe that Windows 7 is THE OS everyone wanted Vista to be. Windows 7 will likely be to Vista what XP was to ME.

Next week I’m going to do a clean install of Windows 7 on my main laptop (Lenovo x301). I have 4 GBs so I’m going to do an x64 install. I’ll report back on my experience.

Posted by dtjones | 3 Comments
Filed under: , ,

Vista Parental Controls Slows Down Zune Marketplace

I’m a huge fan of my Zune and the Zune Marketplace. I have a Zune and my two daughters do as well. I’ve owned several iPods but I just love my Zune more; especially the subscription option for music. $15/month for all the music I want is fantastic. Yes, not everything is included in it and if I stop paying I lose the music but so what. It’s far cheaper in the long run and allows me to explore a lot more music that I otherwise would. I think this is a great way for artists to gain exposure. Anyway, this isn’t the point of the post.

Each of my daughters has their own login to Vista and I’ve setup Parental Controls on their login. This caused a severe performance slow down on the Zune marketplace. Searches and downloads were painfully slow. Running under a full admin account everything worked great. I found one potential solution where the person added 20-something URLs to the allow list. Yuck! That’s not a solution in my book. If one URL changes or another gets added in a software upgrade it’s back to the drawing board. I dug into the Parental Controls stuff in Vista and found a solution. There’s a list of programs that Parental Controls will completely ignore. I added zune.net to the list and viola everything works great. There’s no GUI for this in Vista so it requires editing the registry directly – this means do this at your own risk…

Using information from this site: http://www.bleepingcomputer.com/tutorials/tutorial139.html I added a new value for c:\program files\Zune\Zune.exe under the hive: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Parental Controls\HTTPExemptions. This worked like a charm. What this does is exclude zune.net from Parental Controls. I think this is the best option as I can still control browser access but not impact Zune marketplace performance. It's unfortunate that MSFT doesn't provide a GUI to control this list of programs.

As I said, I love my Zune and so do my girls. They’ve already downloaded a ton of music and exploring a whole new world!

Posted by dtjones | 3 Comments
Filed under: , ,

What’s In Your Database?

How many different database objects are there? I don’t know the answer either but off the top of my head I’d guess somewhere between 50 and 100, depending on how you count them. Yes, I could go count them but I’m writing this on a Saturday and between you and me I’m just too lazy to go do it. If you profiled (not as in SQL Server Profile) your databases what do you think your Pareto chart of objects would look like. I bet it would look something like the following:

image

The scale isn’t important, what is interesting is what objects are most in number and what objects are least in number. If you aggregated this data for all of your database the picture probably wouldn’t change all that much. However, we tend to become obsessed with the right-hand side of the chart. The objects that make up the right-hand side (e.g. triggers, types, etc) are important but sometimes we spend far too much time talking about them at the cost of creating solutions that are simple and easy to use. BTW: I purposefully left off indexes – those will likely out number tables. My point here is we should create tools that make it extremely easy to work with the objects that are in abundance. This includes everything from defining them, deploying them, and managing them after they’ve been deployed.

Everyone likely has a few databases that don’t match this relative distribution but I believe you have far more – at least an order of magnitude if not two – that do. Those database are important as they likely house your most valuable applications; your mission and business critical apps. And we need tools that support those apps and objects as well. But in the process of building tools we shouldn’t make the stuff that should be easy hard. The hard stuff should be possible and the easy stuff should, well, be easy.

In general this approach was taken with IntelliSense in SQL2K8. Yes, there are some things that IntelliSense doesn’t cover. But so what. I know, you’re thinking that’s the stuff we should have covered since you don’t do it all that often and that’s when you need help. if we took that approach – the reverse approach – then you wouldn’t have had IntelliSense for something like table. How lame is that? You’d criticize us for not covering the basic objects. Ok, well, you can probably say we should cover it all. And you’re right. We should. But that’s not always practical. Remember we’re constrained by time and resources just like you are. So we have to make trade-offs. This takes us back to my main point – when we have to make choices we should error on the side of covering the common stuff first. We’re getting better at this but I think we have some major work to do on the common stuff (think table designer in SSMS).

Oh, while you’re profiling your databases don’t forget to count filegroups and files. We recently profiled over 1,000 customer databases that had been consolidated or were on the list to be consolidated. Think of these as departmental apps (they’re not Mission or Business Critical). Only 2-3 databases had multiple filegroups and/or multiple files. This shocked me. But given the average size of these databases was less than 2GBs I shouldn’t be surprised as there was no driver for multiple files.

If you decide to profile some of your databases let me know what you find.

 

Addendum:

We now have customer data on over 1,000 databases. These are DBs that have been consolidated or are candidates for consolidation. Here consolidation means increasing the density of DBs per instance; not increasing the number of apps per DB. Excluding indexes and constraints the average distribution of item types looks like this:

image

This data aligns more closely to what Adam’s (see comments below) has seen in the wild. Adam, thanks for replying and “forcing” me to provide a more real world example of the distribution. :-)

Posted by dtjones | 3 Comments
Filed under: ,

Getting Started in the Community

As an under-grad student @ Cal Poly San Luis Obispo, some 18 years ago, I first experienced the power of the technical community. I was working on a group project to build a little app for the Mac. The class was Software Engineering, CSC440, which covers the entire software lifecycle – requirements, design, implementation and test. My group’s project was to build a search utility for the Mac. Each group member played a different role on the team. I was responsible for writing the code but I was having trouble enumerating all of the hard drives – I couldn’t find the right OS API for this. I know, it seems silly now. I fired up my modem and connected to the university’s newsgroup server and used the comp.mac Usenet newsgroup for help. In the matter of a day (pretty decent latency back then) I had the solution to my problem. Over the course of the next couple of weeks I posted more questions and received answers very quickly.

Community is an important part of a software product. It can serve as tech support and training. Show me a popular product and I’ll show you a strong community standing behind it.

I often get asked the question “if I’m not an expert how can I contribute to the community?” I think a lot of people feel this way. My answer to this is “if you are passionate about the product/technology then you can contribute a lot.” The key, in my book, is to approach it systematically. Here are the steps I recommend to anyone who wants to get involved:

  1. Pick a community (UseNet newsgroups, MSDN forums, SQL Server Central forums, etc)
  2. Pick a topic you are passionate about (PowerShell, T-SQL programming, query performance/tuning, SQL Server Agent, etc)
  3. Pick a few questions that have already been answered and try to find the answer yourself – check your answer
  4. Pick a few questions that haven’t been answered and answer them – this is probably going to take some time as you research the problem and answer.
  5. Pick a few more questions and answer them
  6. Expand to additional communities and answer questions
  7. Collect the more interesting questions and blog about what’s interesting about them
  8. After a few months write a short article on the topic incorporating what you’ve learned over the past few months
  9. Develop a presentation for the article and submit it as a session to a conference
  10. Repeat 5-9

My participation ebbs and flows a bit. When I’m in the game I set aside time each day, 15 minutes or so, answering questions in the forums. You should do the same. And remember, if you use a reference (such as a book) to answer a question site the reference. One other thing – try to use the same username in all of the forums you post and the blogs you write. This gives you name recognition over time. You can go with something dry, like dtjones (my alias @ MS) or something fun like SQL Batman (one of my favorites).

I ended up getting the search utility working and we got an ‘A’ on the project and in the class. If only I had the insight back then to recognize how important and valuable search would become…

Posted by dtjones | 1 Comments
Filed under:

Register for the SQL Server Application and Multi-Server Management Private CTP!

As you probably heard, on Wednesday, November 19th, during Ted Kummert's keynote at the PASS Summit Conference, Microsoft announced future capabilities for application and multi-server management as part of the SQL Server code-name "Kilimanjaro" release.

Participate in a unique opportunity to work with SQL Server Engineers on a totally new concept for developing, deploying and managing applications.Microsoft's investments in application and multi-server management will help reduce the complexity and ambiguity around developing, deploying, and managing applications across the application lifecycle. Through the introduction of a new application model and central management point, organizations will be able to immediately discover and manage SQL Server instances and define deployment policies to simplify database management, optimize resources, streamline collaboration, and help efficiently manage at scale.

Registration: http://www.sqlpass.org/hostedtrial
Posted by dtjones | 3 Comments
Filed under: ,
More Posts Next page »
 
Page view tracker