Stop trigger from inserting new row if ID already exists

Posted on 2007-11-14
Last Modified: 2008-02-01
For some reason we are getting duplicate values inserted into a table with the same foreign key.

As an interim solution i need to stop this happening via a trigger.

Could someone knock up a quick trigger which checks for an ID and if it exists it cancels the insert statement.

Note: The insert statement isn't inside the trigger
Question by:Type25
  • 3
  • 2
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 20278554
maybe putting a unique index (or primary key) on the ID field would even be better, as it would give you the indication where/how these duplicates get inserted...

what do you think?
ie, how do you "generate" those ID values?

Author Comment

ID: 20278589
angelll, i'll be doing this after, for a really quick fix i need to put a trigger in place.
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 20278613
do you have a primary key on the table?

Author Comment

ID: 20278621
Table is like this:

EOWID int primary key
JobNo foreign key
other fields.....

We're getting duplicate job no's.
LVL 142

Accepted Solution

Guy Hengel [angelIII / a3] earned 500 total points
ID: 20278660
create trigger trg_dup_jobno
on yourtable
for insert
  if exists ( select null from yourtable t group by t.jobno having count(*) > 1 )

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now