I need to create an audit trail of changes to stock availablitity through time. Stock is incredibly complex and is made up of physical stock, virtual stock, stock available to order, minimum allowed level, minimum order quantity etc. etc. etc.We have a nice (although complex) view that provides us with all the information we need regarding the various stock values for all items in ours system.We now need to audit this, which is basically a copy of the data at change time with a time loggedBelow is a gross simplification of the issue only dealing with virtual stock.If you run the code as is, you should end up with 2006-11-10 12:37:21.010 1 1002006-11-10 12:37:21.100 1 902006-11-10 12:37:21.110 1 75
output.BUT, I have had to put the trigger on the orders table.I want to to have the trigger on the view (because the view I want to use amalgamates data from all over the place and putting triggers on the individual tables, or amending all the stored procs that affect the stock is going to be a nightmare, esp. as all we want to do is log the view!)I have started playing with instead of triggers (and they are commented out below) but I can seem to get them to work, I was hoping to create a trigger on the view and just being able to the the "inserted" table to log everything I want instead of having to join out to other tables...Could someone please point me in the right direction or am I on a hiding to nothing here?CREATE DATABASE wibblegoUSE wibblegocreate table stock( product_id integer ,stock_quantity integer)gocreate table orders( product_id integer ,quantity integer)gocreate view virtual_stockas select s.product_id ,s.stock_quantity - ISNULL(O.ordered,0) as virtual_stock from stock s left outer join ( select product_id ,sum(quantity) as ordered from orders group by product_id ) as o on o.product_id = s.product_idgocreate table virtual_stock_audit( logged datetime default getdate() ,product_id integer ,virtual_stock integer)goinsert into stockselect 1,100insert into virtual_stock_audit( product_id ,virtual_stock)select 1,100goselect * from virtual_stockgo--TRIGGER ON ORDERScreate trigger t_auditon--virtual_stock ordersafter-- instead of insert, updateas insert into virtual_stock_audit( product_id ,virtual_stock ) select i.product_id ,vs.virtual_stock from inserted i inner join virtual_stock vs on vs.product_id = i.product_idgoinsert into ordersselect 1,10goinsert into ordersselect 1,15gogoselect * from virtual_stock_auditgoUSE [master]goDROP DATABASE wibblego