1
votes

I am not sure if the question title is clear enough, please feel free to edit it.

Basically, I have two DB grids which reflect two database tables, each grid showing one.

When the user selects a row in the first table (let's call it oders), I want to update the second with details of any rows matching a column of the selected row of the first table.

Say, for instance that table orders has a column customer_id and I want to populate the second table (let's call it order_details) with details of all orders from that customer, one order per row.

I can connect up 2 @ datasource, query and connection to the two TDbGrids, but I am stuck as to how to code order_details SQL.

The SQL for orders is just SELECT * from orders, but the other?

I want something like SELECT * from order_details WHERE cutomer_id=<orderQuery>.currentRow.FieldByName("customer_id").AsInteger - but I don't know how to do that ...

Can someone help me with some Delphi code?

Also, once I set up that relationship, will selecting a new row in the orders DB grid automatically update the order_details DB grid? Or do I need to add code for that.

P.s I know that there is no books tag anymore (more's the pity), but can someone recommend a good book which explains the fundamentals of programming DB aware controls? I obviously need one. Thanks

1
It's so called master detail relationship and here's a tutorial for this topic. Maybe this part might be interesting for you, maybe not.TLama
As far as the book recommendation, that question is off-topic here. This isn't a book referral engine. However, any of the older books (those by Cantú, for instance) have chapters on database programming that are a very useful reference for most versions of Delphi.Ken White

1 Answers

4
votes

Use a parameterized query for the detail (child) database:

SELECT * FROM Order_Details od WHERE od.CustomerID = :CustomerID

Then set the child query's MasterSource to the parent (Order) datasource, and the MasterFields to CustomerID. (If there are multiple columns that link the two, separate them by ;, as in CustomerID;OrderNumber.)

Every time you scroll the parent (change the selected record in the parent DBGrid), the child query will be executed with the ID of the parent row passed as a parameter automatically.