Author: Tomas Rutkauskas
On a form, I have a TCheckListBox with records (fields code and name, strings) of a
[ ] 001 - aaaaaaaaaaa
[ ] 002 - bbbbbbbbbbb
[ ] 003 - ccccccccccc
How to build an SQL with only the checked items of the CheckListBox? For example,
SELECT * FROM emp WHERE code = (???)...
You need to inspect all of the items in the TCheckListBox and, for each one
checked, add the text of the item (with quotation marks) to a string to be used for
an IN predicate in the WHERE clause of your statement.
Written manually, your SQL statement might look like this (for the first two items
WHERE code in ("aaaaaaaaaaa", "bbbbbbbbbbb")
Done programmatically, it would look something like this:
2 InPredicate: string;
3 i: Integer;
5 InPredicate := '';
6 with Query1 do
8 for i := 0 to (CheckListBox1.Items.Count - 1) do
9 if CheckListBox1.Checked[i] then
10 InPredicate := InPredicate + '"' + CheckListBox1.Items[i] + '",';
11 System.Delete(InPredicate, Length(InPredicate), 1);
13 SQL := Format('WHERE State IN (%s)', [InPredicate]);
Of course, this assumes the SQL statement starts out with a WHERE clause and this
filter will always be on the third line. At any rate, that routine demonstrates
dynamically building the values list for the IN predicate.
If you have too many items in that TCheckListBox, it might be possible to exceed the maximum length of a line in the TQuery.SQL property (255 characters). In such cases, you would need to add checking for this and account for building the filter across multiple lines in the SQL statement.