I have two tables; ItemTable and ProductTable. ProductTable's ItemID column links to ItemTable's ID column. The ID columns of both tables are primary keys and identity columns.
Like this:
ItemTable:
ID Col ColOther Latest Time
100 'old' 'oldother' 1 <Autogenerated timestamp>
ProductTable:
ID ItemID Value ValueOther Latest Time
12 100 'foo' 'bar' 1 <Autogenerated timestamp>
Whenever I want to manually UPDATE a row in the ItemTable, which would normally be done in just one query:
query = \
"""
UPDATE ItemTable
SET Col = ?, ColOther = ?
WHERE ID = 100;
"""
cursor.execute(query, 'new', 'newother')
Instead of just doing the UPDATE like above, I would like to do these things for ItemTable:
- Automatically
UPDATEthe old row to haveLatest = 0 INSERTthe row with the updated values, andLatest = 1(Let's say this row gets theID250)
Then for the ProductTable:
- Automatically
UPDATEthe old linking row in the ProductTable to haveLatest = 0 - And automatically
INSERTthe same row with the newItemIDandLatest = 1
This automatic INSERT and UPDATE would preferably happen with just a pure SQL query (perhaps using OUTPUT, but I'm not familiar with that), alternatively it could be implemented with some Python code. How would I go about doing this?
The wanted end result:
ItemTable:
ID Col ColOther Latest Time
100 'old' 'oldother' 0 <Autogenerated timestamp>
250 'new' 'newother' 1 <Autogenerated timestamp>
ProductTable:
ID ItemID Value ValueOther Latest Time
12 100 'foo' 'bar' 0 <Autogenerated timestamp>
110 250 'foo' 'bar' 1 <Autogenerated timestamp>