x

avoid duplicates using triggers

Hi,

A table has no primary key column, Need to write a trigger which should not allow any duplicate values.

more ▼

asked Jan 18, 2010 at 05:54 AM in Default

Mohan gravatar image

Mohan
324 37 55 60

(comments are locked)
10|1200 characters needed characters left

2 answers: sort voted first

What is the reason to not have a primary key? Do you really need a trigger?

If you need to prevent duplicates I would recommend you to have a primary key or unique (clustered?) index. Why? If you use a trigger to search for duplicates you will also need an index to get performance. If you don't use an index that match your condition you will end up with a slow table/index/heap scan.

more ▼

answered Jan 18, 2010 at 06:21 AM

Håkan Winther gravatar image

Håkan Winther
15.6k 34 37 48

+1 - a trigger is not the way to go here, listen to Håkan's advice.
Jan 18, 2010 at 06:37 AM Matt Whitfield ♦♦
+1 - the clustered index is the best bet, unless there is a local requirement that you havent mentioned that prevents it.
Jan 18, 2010 at 07:08 AM Fatherjack ♦♦
+1 must say your answer was better formulated that mine, and you were faster :-)
Jan 18, 2010 at 11:51 AM Steinar
Thanks Steinar! Better luck next time! :-)
Jan 18, 2010 at 12:32 PM Håkan Winther
A clustered index will require every row to be moved around. A non-clustered unique index (otherwise known as a unique constraint) would be better, and can still be used for Foreign Keys.
Jan 18, 2010 at 08:01 PM Rob Farley
(comments are locked)
10|1200 characters needed characters left

You could also use a unique constraint/unique index. http://msdn.microsoft.com/en-us/library/aa224827(SQL.80).aspx

more ▼

answered Jan 18, 2010 at 06:16 AM

Steinar gravatar image

Steinar
1.7k 3 4 6

(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x117

asked: Jan 18, 2010 at 05:54 AM

Seen: 2010 times

Last Updated: Jan 18, 2010 at 05:54 AM