Re: Preventing Duplicate Records in Delphi

Bby webmaster Guido on September 21, 2001

In Reply to: Preventing Duplicate Records in Delphi posted by Lisa Whyte on September 21, 2001

: Is there a way to prevent duplicate records in Delphi while using tables? Thanks for your help :)


In fact, this depends from the type of table that you are using and from the index type. Basically, there are two approaches to this:

1. If your table has a *unique* index (primary index), it's impossible to add a duplicate record. A new record, with a value in the primary index field that is the same as an already existing record, is simply not allowed, it is not "posted" by Delphi. In that case, Delphi will also generate a "Key violation" error.
If you don't handle the resulting "exception", Delphi will just show a message saying "Key violation".
If you handle the error, you can display your own message, telling the user that "A record with the value 'X' in field 'Y' already exists. Please, enter another value."

So, if the table doesn't have a unique index, create a unique index by indicating one of its fields as the "key" index-field (e.g. Book_ID in a table of books, Customer_ID in a table of customers, and so on...)

2. Or: right before the record is posted, open the same table using a second TTable-component, say "TTable2". Next, check if the record already exists in TTable2:
- if no, do nothing;
- if yes, display an error message and don't allow the posting of the record in your original TTable component.

___________________________________________________________

If this is not clear, please ask for more info in this forum, and give use some more details:

- the table type: Paradox, dBase,...?
- is the table indexed, and if yes, on what fields? Is there a *unique* index?
- is adding of records done "automatically", using a DBGrid, or under program control (such as: click a button "Add record", fill in some DBEdits, click a button "Post record")?
- are you using Delphi's built-in BDE engine (Borland Database Engine), or maybe an external database system that doesn't use the BDE, such as Topaz, Apollo,...?


Related Articles and Replies


[ DelphiLand FAQ ] [ Delphi Tutorials ]