Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 unique constraint on two columns

Author  Topic 

markman
Starting Member

2 Posts

Posted - 2005-02-24 : 19:59:22
Hi, I'm fairly new to sql server and I am trying to ensure that two columns have unique values:

TestTable:

Id bigint (primary)
col1Id bigint
col2Id bigint

on each insert I want to ensure that the COMBINATION of col1Id and col2Id is unique.

How do I implement such a thing?

Thanks, Mark

Ex
Posting Yak Master

166 Posts

Posted - 2005-02-24 : 20:05:03
might be a better way but
can create a unique index


CREATE UNIQUE INDEX indexName ON TestTable (col1Id, col2Id)
Go to Top of Page

robvolk
Most Valuable Yak

15732 Posts

Posted - 2005-02-24 : 20:05:34
ALTER TABLE TestTable WITH CHECK ADD CONSTRAINT UNQ_Col1ID_Col2ID UNIQUE (Col1ID, Col2ID)
Go to Top of Page

robvolk
Most Valuable Yak

15732 Posts

Posted - 2005-02-24 : 20:07:15
You can use a unique index too, a unique constraint creates a unique index.

If both columns must be unique, why not make them the primary key? Then you can drop the ID column.
Go to Top of Page

markman
Starting Member

2 Posts

Posted - 2005-02-24 : 21:18:11
thanks for the help, I agree that I should drop my primary key since col1 and col2 effectively establish a primary key but it's easier for me to keep it. I finally was able to add a unique constraint on the two columns and it seems to work. Thanks again.
Mark
Go to Top of Page
   

- Advertisement -