Topic: Checking Database for existing record

Hi there, we are writing a database where one of our tables contains Colours.
The first column is a four digit Colour key i.e BLAC for Black. If a user tries to add BLAC for a new record how do we check if it already exists and if it does advise the user if already exists?
We need the four digit key to be unique to avoid multiple entries of the same.
Thank you
Jason

Re: Checking Database for existing record

Hello Jason, (and all other users, long time no see)


The kind of problem you will encounter very often.


What you could do is :

  • load the list of color names in a dataset

  • search the dataset for existing name


Fortunatly, this is something easily done because Delphi is awesome !!


You'll have to check BEFORE the insert is triggered.

To load the color abbreviation into a dataset, simply do something like :

procedure Form1_Button1_OnClick (Sender: TObject; var Cancel: boolean);
var
    ColorList : TDataset; //to store the abreviation list
    ColorAbrev : String;  //to get user input
begin
    //get the user input from the edit field on the form
    ColorAbrev := Form1.edit1.text;

    //load the list of existing abreviation to the ColorList dataset
    SQLQuery('SELECT color_name FROM dbcolors',ColorList);
        //try and match the database field (named color_name here), with the input variable
        if ColorList.Locate('color_Name',ColorAbrev,0) then
            begin
                //warn the user with your own message
            end else
            begin
                //execute the query to add the new record to the color table
            end;
end;

The "locate" function will return -1 if no match is found but with the if / else structure, you are good as well.


I believe the 0 flag at the end corresponds to a case insensitive search, there might be other flags like 'partial find', but you'll have to ask Dmitry.


Hope this helps.


Cheers


Mathias

I'm a very good housekeeper !
Each time I get a divorce, I keep the house

Zaza Gabor

3 (edited by derek 2020-12-17 10:34:40)

Re: Checking Database for existing record

Hi Jason, Hi Mathias (good to know that you're still around - hope you and the family are well).
Welcome to MVD.
There are a few different ways of testing for a duplicate;  which one suits best depends on your particular application, whether you want to trap the duplicate at time of entry or when trying to save the record etc etc.
Please see the attached as one very simple way of checking.
Regards,
Derek.

Post's attachments

Attachment icon duplicate.zip 337.02 kb, 257 downloads since 2020-12-17 

Re: Checking Database for existing record

Hi Derek, Hi Mathmatou

Mathmatou,, glad to see your feedback on the MVD forum.
I hope you're okay

JB

Re: Checking Database for existing record

Thank you everyone for your replies, with our assistance i have resolved the issue. smile