Creating A Unique Constraint
I forgot all about creating UNIQUE constraints. Of course I would have a need for it, and you know it goes into the eBrain.
Basically there are two ways to create a UNIQUE constraint. You can do it via TSQL, or using the SQL Server Management Studio (SSMS).
TSQL
ALTER TABLE tblMyTableName ADD CONSTRAINT MyConstraintName UNIQUE(myColumnName);
Pretty simple there eh? tblMyTableName is the name of your table, MYConstraintName is what you want to call this constraint. myColumnName is the column or field I want to make UNIQUE.
SSMS
The next part is how to add it with SSMS. This isn’t too hard either. In SSMS go to the database where you want this constraint. Right click the table where you want this constraint. Click Design.
In the designer go to the top and click Manage Indexes and Keys, it is a little icon that looks like a key on top of a table.
In this new window click the Add button. In the General section you will need to select the Column you want UNIQUE. For the Type pick Unique Key. Of course you will need to give it a name.
Remember, a UNIQUE column can still hold a NULL, but only one record can have that NULL value so that NULL is unique.
Posted on June 26, 2012, in SQL and tagged CONSTRAINT, SQL. Bookmark the permalink. 1 Comment.
You are quite correct. Thank you very much for your input. I have to admit, for most tables I usually only have one primary key field. My friends who do a lot of BI Reporting do make use of multiple indexes.