Default Constraint NamesBy Bill Graziano on 24 January 2001 | Tags: Table Design A DBA I know named Lance sent me a view and a write-up on it and asked if I'd like to publish it. He posts in the forum under JohnDeere. Lance was fighting with server named default constraints and was using the view to help manage and rename the constraints.
When you create a table in SQL Server you can add various constraints to the table. One of the constraints you can add is a default contstraint. Your CREATE TABLE might look like this:
CREATE TABLE Test1 (Val1 int DEFAULT -1, Val2 int DEFAULT -2, Val3 int DEFAULT -3 ) SQL Server will assign each default constraint default a default name. In my case it named the first default constraint This doesn't cause you any problems until you try to change one of the defaults. In order to alter a constraint, you need to know the name of the constraint. The code to change the default value from -1 to -9 looks like this:
This becomes important in rolling out new databases or keeping multiple copies synchronized. The problems that Lance faced were compounded by the fact that he had four databases on two remote servers. Lance created a view to help him identify the default constraints and rename them. Here's his view:
After that, all Lance needed to do was drop the constraints and recreate them using a naming scheme he defined. All that took was a little dynamic SQL and SQL Server do the work. Lance's advice was to always name your constraints. Especially if you are using scripts to rollout or modify databases. This works much better if the initial CREATE TABLE looked like this:
It's a little more work up front but worth it if you're going to be working in a multiple server environment.
|
- Advertisement - |