I have the following tables:
1) TBL (ID, Data, LastUpdated, DateCreated)
2) TBL_LOG(Log_ID, LogCreateDate, ID, Data, LastUpdated, DateCreated)
TBL used to store current data and TBL_LOG used to store every change of data in TBL (using update trigger, the deleted record from TBL copied to TBL_LOG).
Now I need to retrieve the data by relevance date.
How I can write the table valued function (or other alternative) that will return the data depending on RelevanceDate.
I understand the logic, but I can’t find a good way to write it in SQL…
The logic looks like:
@RelevanceDate = '2011-03-01'
IF TBL.LastUpdated <= @RelevanceDate THEN return data from TBL
ELSE IF Exists data in TBL_LOG where TBL_LOG.LastUpdated <= @RelevanceDate
THEN return most resent data from TBL_LOG where TBL_LOG.LastUpdated <= @RelevanceDate
ELSE IF Exists data in TBL_LOG where TBL_LOG.LastUpdated > @RelevanceDate
THEN return the oldest data from TBL_LOG.LastUpdated > @RelevanceDate
ELSE return data from TBL
This function should return data using the logic above, for all records in TBL.
In short words, for each row in TBL i need data that was on “RelevanceDate”.
At the end of my investigation, i ended up with something like folowing:
If someone have a suggestion how it can be done in better way, i will glad to see it 🙂