I have a lot of related tables that are also system-versioned, and I am having difficulty specifying the version of data that I want pulled into one table from another table.
For example, I have an "Account" table with the primary key "Account No". It also has a "Version No" field that is incremented each time an account or its child data is altered.
There is also a child table "Account_General" that contains the "Name" of each account. The primary key, "Account No", is also a foreign key relating it back to the parent table "Account".
I also have a "Contact" table with the primary key "Contact No". Each contact is associated with an account via a foreign key on "Account No". The version of the account that the contact was created under is also recorded via an "Account Version No".
I am trying to create a view for the Contact table that will pull the account "Name" based on the "Account No" and "Account Version No". I was hoping to use the "Valid From" date on the account version to reconstruct the account data at the time of the version specified in the contact table using the FOR SYSTEM_TIME AS OF clause and subclause. Something like this...
SELECT c.[Contact No],
ag.[Name]
FROM [Contact] c
JOIN (
SELECT ag.[Account No],
ag.[Name]
FROM [Account_General]
FOR SYSTEM_TIME AS OF (
SELECT a.[Valid From]
FROM [Account]
FOR SYSTEM_TIME ALL a
WHERE a.[Version No] = c.[Account Version No]
)
) ag
ON c.[Account No] = ag.[Account No]
However, this is giving "Incorrect syntax" errors for the SELECT subquery within the "AS OF" subclause.
Instead of recording the account's version number in the contact table, I could record the "Valid From" date at the moment the account is assigned to the contact. This isn't my preference as "Version No" is more readable and, on the front end, users will be given some control over which version of the account they want the contact associated. However, if this yields a better solution, I'm open to switching "Version No" for an "As Of" date/time.
In fact, I have a lot of control over the table structure here, so if there is a different way entirely that would better accomplish what I'm trying to do, then I'm all ears.