Friday, November 27, 2026

Creating a complicated query

I was working on a form in the OP's "ERP" program that contains data about contacts; one of the fields is the contact's email address and I thought it important that I keep track of changes in the address. While I was doing this, it occurred to me that it would be a neat hack to change the keyboard language to English for this field only. On the program's startup, the existing keyboard layout is saved and then the keyboard is instructed to use the Hebrew layout. For this email address field, I would need to do the opposite: save the layout then set the layout to English. When the focus leaves this field, the layout - presumably Hebrew - would be restored. This was very easy to do.

procedure TEditContact.edEmailEnter(Sender: TObject); var ahkl: HKL; begin layout:= GetKeyboardLayout (0); ahkl:= LoadKeyboardLayout ('00000000', KLF_NOTELLSHELL); ActivateKeyboardLayout (ahkl, KLF_ACTIVATE); end; procedure TEditContact.edEmailExit(Sender: TObject); begin ActivateKeyboardLayout (layout, KLF_ACTIVATE); end;

A day after having done this, it occurred to me that I could do the same with the EditTherapist form - therapists too have email addresses. So I added the above code and also the query that saves data about changes in the email (the table is called ContactChanges), but I needed to add a field to ContactChanges to distinguish whether the contact number came from the contacts table or whether it was a therapist. A few hours later I did the same for the EditContact2Cust form.

Every day I would check to see whether there was any data in this table but it took a few days until there were a few entries (I don't expect there to be many). Then I was faced with the problem of displaying the data; as they could come from three different tables, at first I wasn't too sure whether it would be better to write three queries that feed their data into a memtable for display or whether I should write a humungous 'union all' query or even whether I could combine everything into one query, albeit complicated. The fact that there would be several parameters that would have to be repeated in the first two solutions convinced me that it would be better to go with the one complicated query.

Let's start with the 'select' clause: the first two fields were straight-forward: select contactchecks.curdate, users.name, . Then I wanted to show what type of the data is displayed: contact, therapist or customer contact. This would require a case statement - wordy but relatively simple. Again, I used a case statement to display the name of the person whose email was being edited. Finally came the old and new email addresses; as these are stored in the ContactChanges table, this was easy. So the first part of the query looked like this:

select cc.changedate, users.name, case when cc.sug = 'C' then 'איש קשר' when cc.sug = 'T' then 'מטפל' when cc.sug = 'A' then 'איש קשר ללקוח' else 'אחר' end as ctype, case when cc.sug = 'C' then c.cname when cc.sug = 'T' then t.name when cc.sug = 'A' then c_a.cname else '' end as contactname, customers.name, cc.oldemail, cc.newemail from contactchanges cc inner join users on users.id = cc.userid

When I showed this to CoPilot, it was suggested that the second case statement was unnecessary - I could use the 'coalesce' function to show the contact name, viz. coalesce (c.cname, t.name, c_a.cname) as contactname,. Regarding the various joins, I assumed that these would be left joins dependent on the value of cc.sug. The only complication with this was that the contact2cust table required another two joins: one to another instance of the contacts table and one to the customers table. So this part became

left join contacts c on c.id = cc.contact and cc.sug = 'C' left join therapists t on t.id = cc.contact and cc.sug = 'T' left join contact2cust on contact2cust.id = cc.contact and cc.sug = 'A' left join contacts c_a on c_a.id = contact2cust.contact left join customers on customers.id = contact2cust.customer

The 'where' clause would start as usual with where 1 = 1, so that any additional conditions would always start with 'and'. The user could enter one of three parameters: from date, till date and user; this is commonplace in the program. I also allowed the 'not' function that I appear not to have documented here (as in and not user.id = :p2). The final unusual twist was that I wanted to allow the user the option to display any combination of contacts, therapist and customer contacts - the interface sported three appropriate checkboxes. At first I thought to do this with a set and then have the comparison and cc.sug in [..] but this would make building the set complicated. CoPilot had a different idea:

// whilst still building the query text s:= s + ' and ((:p3 = 1 and cc.sug = ''C'') '; s:= s + ' or (:p4 = 1 and cc.sug = ''T'') '; s:= s + ' or (:p5 = 1 and cc.sug = ''A''))'; // after adding parameters for date and user parambyname ('p3').asinteger:= ord (cbContacts.checked); parambyname ('p4').asinteger:= ord (cbTherapists.checked); parambyname ('p5').asinteger:= ord (cbContact2Cust.checked);

This is an interesting technique, but it would only work for a few well-defined values. To sum up: one query with one case statement, one coalesce, several tables with left joins and an interesting way of choosing which data to display.



This day in blog history:

Blog #Date TitleTags
14727/11/2008AchievementsProgramming, ERP
118727/11/2018Intermediate thesis accepted!!DBA
127627/11/2019Song festival 2019 - 2Song writing
135927/11/2020Preparing for the DBA vivaDBA
155627/11/2022Communal griefObituary, Kibbutz

Thursday, November 26, 2026

Editing check boxes in a DBGrid - revised

A year and a half ago, I wrote about editing check boxes in a DBGrid1; this was in 'the good old days' of Delphi 7 and dbExpress components. I had occasion to revisit a unit that used this code and found that it didn't work with Delphi 12CE and FireDAC, primarily because the grid was buffered with a memtable. After working with CoPilot on a solution and then working alone to improve that solution, I now present a new approach to editing check boxes in a DBGrid. Apart from anything else, this code also prevents the 0 and 1 that would appear using the old solution.

First, two clarifications to the previous code: there is no need to define columns in the grid, and the dgEditing flag in the grid's options should not be set. Thus there's no possibility of changing a value in a text field. The check box's value is changed by simply clicking on the check box: this is handled in the OnCellClick method of the grid. The check at the beginning if sametext (fn, 'finance') prevents anything bad happening if the user clicks on a field that is not drawn as a checkbox. The sametext function fixes any problems that might occur if one parameter is in upper case and another is in lower case (or in CamelCode format). 

procedure TShowContact2Cust.DBGrid1CellClick(Column: TColumn); var fn: string; begin fn:= DBGrid1.SelectedField.FieldName; if sametext (fn, 'finance') or sametext (fn, 'report') or sametext (fn, 'miyun') or sametext (fn, 'call') then begin ToggleCheckBox (dbgrid1.selectedfield); qUpdate.macrobyname ('fieldname').asraw:= fn; qUpdate.params[0].asinteger:= mtContact2CustID.asinteger; qUpdate.execsql; dbGrid1.EditorMode:= false; end; end;

qUpdate is required in this form as the grid's dataset is a memtable; in another form there is no memtable sitting between the database and the grid and so qUpdate is not required there. This query uses a macro, thus enabling it to update any one of the four fields without having to manipulate the query's text.

update contact2cust set !fieldname = 1 - !fieldname where id = :p1;

The ToggleCheckBox procedure is very simple and uses a trick that avoids having to test whether the parameter belongs to a memtable or a query.

Procedure ToggleCheckBox (sf: tfield); begin sf.DataSet.Edit; sf.AsInteger:= 1 - sf.AsInteger; sf.DataSet.Post; end;

And that's all the code that is necessary. Much simpler than what went before.

Internal links
[1] 1935



This day in blog history:

Blog # Date Title Tags
1443 26/11/2021 Opening Excel from a thread and displaying a file Programming, Delphi, Office automation, Threads
1690 26/11/2023 Guitar thoughts Guitars
1866 26/11/2024 Delphi logging Programming, Delphi