I have a table in SQL Server with three columns: col1, col2, col3. I have inserted a row with values 1,2,3, and it should not repeat again. Through a trigger, how it is possible to restrict a user from inserting the same values? I don't want to create primary keys, or even any identity columns. It should not be allowed to insert 1,2,3, but one could insert 1,2,5 and 1,2,4.
May I suggest a UNIQUE constraint.
alter table yourtable add constraint nodupes123 unique nonclustered ( col1, col2, col3 )
You could get the same result using a trigger, but why? In the trigger code, you would have to do a SELECT to see if any row exists already with the particular values for the three columns, and this SELECT is going to be inefficient unless there is an index defined on those three columns. You might as well define the UNIQUE constraint because this creates the index automatically, and then you don't have to write any code.
For More Information
- Dozens more answers to tough SQL questions from Rudy Limeback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
Dig Deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.