4

I have a Product table in my DB with following columns :

ProductId INT IDENTITY PRIMARY KEY
ProductCode VARCHAR(100) NOT NULL
ProductStamp VARCHAR(100) NOT NULL

I need both ProductCode and ProductStamp unique for example :

Allowed

Code Stamp
---- -----
A001 S001
A002 S002

Not allowed

Code Stamp
---- -----
A001 S001
A001 S002

How to achieve this? Thank you very much

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
tickwave
  • 3,335
  • 6
  • 41
  • 82

3 Answers3

9

Unique constraint on a single column:

ALTER TABLE Product ADD CONSTRAINT AK_Product_ProductCode UNIQUE( ProductCode )
ALTER TABLE Product ADD CONSTRAINT AK_Product_ProductStamp UNIQUE( ProductStamp )

These will raise an error if there are two rows with duplicate product codes, OR product stamps.

Unique constraint on a multiple columns:

ALTER TABLE Product ADD CONSTRAINT AK_Product_ProductCodeAndStamp UNIQUE( ProductCode, ProductStamp )

This will fire if there are two rows with code AND stamp the same.

The convention "AK" for naming stands for "Alternate Key"

xan
  • 7,440
  • 8
  • 43
  • 65
1

You need to add a Unique Index:

CREATE UNIQUE NONCLUSTERED INDEX [IX_NAME] ON [your_table] 
(
    ProductCode

) WITH IGNORE_DUP_KEY;
Lewis86
  • 511
  • 6
  • 15
Galma88
  • 2,398
  • 6
  • 29
  • 50
0

Based on your needs, I would recommend using a unique constraint or unique index to the column(s) you need uniqueness enforced by the database.

Note that a unique constraint is not indexed in any way, so if you have a lot of use for the unique columns in where clauses (or in joins), you will probably want to use an index.
If not, a unique constraint would be better in terms of storage size and insert/update costs.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121