We have following requirement :
Table1: composite primary key version, id
------------------------------------
version id col1 coll2 active
------------------------------------
1 123 'A' 'B' 'N'
2 123 'C' 'D' 'Y'
1 124 'E' 'F' 'Y'
Now for any insert and update on table1 for a given id, a new row should be created with the following attributes (derived by a trigger):
Versionshould be incremented by 1 for givenidand- most current row should become active (
activecolumn is set toY)
e.g.
INSERT INTO table1(id, col1, col2) VALUES (123, 'X', 'Y');
------------------------------------
version id col1 coll2 active
------------------------------------
1 123 'A' 'B' 'N'
2 123 'C' 'D' 'N'
3 123 'X' 'Y' 'Y'
1 124 'E' 'F' 'Y'
3rd row is created
UPDATE table1 SET col1 = 'F' WHERE id = 124;
------------------------------------
version id col1 coll2 active
------------------------------------
1 123 'A' 'B' 'N'
2 123 'C' 'D' 'N'
3 123 'X' 'Y' 'Y'
1 124 'E' 'F' 'N'
2 124 'F' 'F' 'Y'
last row is created
DELETE FROM dbo.table1 WHERE id = 124;
------------------------------------
version id col1 coll2 active
------------------------------------
1 123 'A' 'B' 'N'
2 123 'C' 'D' 'N'
3 123 'X' 'Y' 'Y'
1 124 'E' 'F' 'N'
2 124 'F' 'F' 'N'
all rows for id 124 become inactive.
This seems to be modeling issue , but we are mandated to provide this feature using TABLE1 and supporting triggers.
We are not able to get around modifying the table issue as we need to select max(version)
and then insert into same table, Can anyone please suggest a workaround ?
I don’t like the database design, it’s horrible, but you say you are stuck with it. How about using a view with INSTEAD OF triggers?
1) Rename the table to e.g. TABLE1_BASE
2) Create view TABLE1 as SELECT * FROM TABLE1_BASE
3) Add an INSTEAD OF trigger like this:
(Something like that)