I have a simple database with 4 tables:
- Customer (cusId)
- Newspaper (papId)
- SubCost (subId)
- Subscription (cusId, papId, subId)
Newspaper has a column to track number of subscribers which is updated via a trigger on the Subscription table. It also has a column to track annual revenue which should be based on the number of subscribers and the cost associated with the subscription (subId).
I am looking for a trigger to track annual revenue. There are 3 subscription types (subId) with differing weekly costs and a paper can have more than one type of subscription so it can't just be (cost * 52 * numSubs).
Can you help me with this logic?
Your best bet is not using such a column at all. Instead use a view which computes the result, and index it if necessary
If you decide to index the view, be aware there are many restrictions to indexed views, in particular:
INNER JOINis allowed, no other join types, no subqueriesCOUNT_BIG(*), and the only other aggregation allowed isSUMWITH (NOEXPAND)hint when querying, otherwise there may be performance impactsThe server will automatically maintain the index, you do not need to update it.