I have three tables:
Orders:
orderid, valuedid, valuesdesc
Customers:
customerid, cutomdesc
Groups:
groupid, groupdesc
valueid – id of a customer or a group
valuesdesc – must filled with appropriate for inserted valueid description from Customers or Groups depend on what (customer or group) user selected in the client.
So, when client send an insert query for Orders it consists orderid for new order and valuedid. And on a client side I know what user selected: group or customer.
What I need: if a new row inserted in Orders, corresponding valuesdesc for valuedid from Customers or Groups inserted in valuesdesc column.
I have an idea to insert with new order record valuesdesc which would contain key – fake value to pick the right dictionary (customers or groups), but how to create that trigger I unfortunately don’t know for now.
First, I must say this is a very uncommon design. When you are inserting a record into
Orders, you usevaluesdescto hint at the table thatvalueidreferences. But as soon asvaluesdescgets filled by the trigger,valueidessentially loses any meaning. That is, you haven’t reveal us you’ve got any other way to tell a reference toCustomersfrom a reference toGroups. So, you could just as well dropvalueidaltogether and usevaluesdescto pass both the ‘dictionary’ hint and the reference within that table.Other than that, because
valueidcan reference more than one table, you cannot use a foreign key constraint on it.Anyway, in your present design you could try this:
The strings
'Customers'and'Groups'are meant as the dictionary specifiers. You replace them with the actual values.The trigger uses LEFT JOIN to join both
CustomersandGroups, then fillsOrders.valuesdescwith eithercustomdescorgroupdesc, depending on which one is not null.