I have a base table and a history table. The history table contains 5 extra columns:
surrogate keyinsert_dateend_dateold_addressflag
In the history table I want to record data changes of the base table. If there is any change of a row in the base table then a new row should be inserted to the history table that records this change.
My input data is
student_id name city state mobile
1 suraj bhopal m.p. 9874561230
2 ravi pune mh 9874563210
3 amit patna bihar 9632587410
After this insert my target table would be like this
surr_key student_id name city state mobile insert_Date end_date old_add Flag
1 1 suraj bhopal m.p. 9874.. 31/06/2015 31/12/9999 bhopal Y
2 2 ravi pune mh 9874.. 31/06/2015 31/12/9999 pune Y
3 3 amit patna bihar 9632.. 31/06/2015 31/12/9999 patna Y
When inserting a new row into the base table an appropriate row should be inserted into the history table and the insert_date and end_date of this row should be same and flag shoud be set to 'Y'. After updating this row in the base table a new row will be inserted in the history table to reflect the changes made to the row of the base table. The insert_date will be set to the current date (sysdate) and end_date will be set to '31-12-9999' for the new row of the history table and for this row flag is set to 'Y' and the flag of the old row is updated to 'N'.
So the row of the history date that recorded the last change of a row in the base table has the column Flag set to 'Y'. All other rows that recorded changes of this base table row have the Flag set to 'N'.
Something like this-
surr_key student_id name city state mobile insert_Date end_date old_add Flag
1 1 suraj bhopal m.p. 9874.. 31/06/2015 31/12/9999 bhopal N
2 2 ravi pune mh 9874.. 31/06/2015 31/12/9999 pune Y
3 3 amit patna bihar 9632.. 31/06/2015 31/12/9999 patna Y
4 1 pradeep bhopal m.p. 9874.. 31/06/2015 31/12/9999 (null) Y
If the update is only on the city then the new change should be in city and the previous name of city should be put in old_add column
Like this-
surr_key student_id name city state mobile insert_Date end_date old_add Flag
1 1 suraj bhopal m.p. 9874.. 31/06/2015 31/12/9999 bhopal N
2 2 ravi pune mh 9874.. 31/06/2015 31/12/9999 pune Y
3 3 amit patna bihar 9632.. 31/06/2015 31/12/9999 patna Y
4 1 pradeep bhopal m.p. 9874.. 31/06/2015 31/12/9999 bhopal Y
If, there is a condition that both address and some other record let say name is updated then for that a new row should be there and old address should be updated.
surr_key student_id name city state mobile insert_Date end_date old_add Flag
1 1 suraj bhopal m.p. 9874.. 31/06/2015 1/09/2015 bhopal N
2 1 suraj bhopal m.p. 9874.. 2/09/2015 31/12/9999 indore Y
Is it possible without using any trigger as I don’t want to use it I just simply want a query. Can anyone help???