Articles   Members Online:
-Article/Tip Search
-News Group Search over 21 Million news group articles.
-Delphi/Pascal
-CBuilder/C++
-C#Builder/C#
-JBuilder/Java
-Kylix
Member Area
-Home
-Account Center
-Top 10 NEW!!
-Submit Article/Tip
-Forums Upgraded!!
-My Articles
-Edit Information
-Login/Logout
-Become a Member
-Why sign up!
-Newsletter
-Chat Online!
-Indexes NEW!!
Employment
-Build your resume
-Find a job
-Post a job
-Resume Search
Contacts
-Contacts
-Feedbacks
-Link to us
-Privacy/Disclaimer
Embarcadero
Visit Embarcadero
Embarcadero Community
JEDI
Links
How to check for a duplicate key index programmatically Turn on/off line numbers in source code. Switch to Orginial background IDE or DSP color Comment or reply to this aritlce/tip for discussion. Bookmark this article to my favorite article(s). Print this article
Check for a duplicate key index programmatically 28-May-03
Category
Database Others
Language
Delphi 3.x
Views
149
User Rating
No Votes
# Votes
0
Replies
0
Publisher:
DSP, Administrator
Reference URL:
DKB
			Author: Tomas Rutkauskas 

I have a DBISAM 2.04 table with several indexes. It actually lists project details. 
One field is the ProjectNo (a text field some 20 char wide). I want to make sure 
that the same PropjectNo is not entered twice. I could make the index unique, and 
that would no doubt work. But the error message returned in not very user friendly 
- I would rather trap it myself. I assume that in the OnBeforEInsert event I would 
have some code that checks to see if this index key already exists. If so, then I 
warn the user (perhaps even allowing the record to be saved if the user insists). 
And then aborting the save if a duplicate. How do I find an existing key, i.e. 
something like KeyExists(['99023']) ? Would I have to do a Locate or something?

Answer:

Make a generic function like:
1   
2   function TMyForm.CheckDuplicateKey(ATable: string; const Field: TField): Boolean;
3   var
4     cSQL, KeyField, cValue: string;
5   begin
6     KeyField := Field.FieldName;
7     cValue := Field.AsString;
8     cSQL := Format('select %s from %s where %s = %s', [KeyField, ATable, KeyField,
9       cValue]);
10    with LookupQuery do
11    begin
12      SQL.Clear;
13      SQL.Add(cSQL);
14      Open;
15      if RecordCount > 0 then
16        Result := True
17      else
18        Result := False;
19      Close;
20    end;
21  end;
22  
23  //and use it in your key field's OnValidate handler like:
24  
25  procedure TMyForm.MainQueryMyIDValidate(Sender: TField);
26  begin
27    if CheckDuplicateKey('MyTable', Sender) then
28      raise Exception.Create('The table already has a record with this key.');
29  end;



			
Vote: How useful do you find this Article/Tip?
Bad Excellent
1 2 3 4 5 6 7 8 9 10

 

Advertisement
Share this page
Advertisement
Download from Google

Copyright © Mendozi Enterprises LLC