Seed data with old dates in Temporal Table - SQL Server

后端 未结 4 568
没有蜡笔的小新
没有蜡笔的小新 2020-12-16 01:00

I need to seed data for my local development purpose in the following Temporal Table, the start date should be old. The given Table Schema is

CREATE TABLE [d         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 01:43

    What are you trying to achieve? The GENERATED ALWAYS columns are technical columns and if you set them as that you can't update them, they are updated automatically. For tracking changes you have ContactHistory table.

    Normally you are supposed to use following INSERTs:

    INSERT INTO dbo.Contact
    (
        ContactID, --NEWID()
        ContactNumber
    )
    VALUES
    (
        '045ABA61-1C64-4FE4-B079-18A9A50335D5', -- ContactID - uniqueidentifier
        N'9999912345'
    );
    

    Then after the first insert this is what you have:

    select * from dbo.Contact
    select * from dbo.ContactHistory
    

    You do not have any records in history yet as it doesn't store the actual record. Now if you would like to change the data, then you use normal UPDATE statements ignoring these GENERATED ALWAYS columns:

    UPDATE dbo.Contact SET ContactNumber = '123456789' WHERE ContactId = '045ABA61-1C64-4FE4-B079-18A9A50335D5'
    

    Let's check the data again:

    select * from dbo.Contact
    select * from dbo.ContactHistory
    

    Now you have a bit different situation:

    As you can see that the actual data is updated as expected and the history table has the old record with the "closed" EndTime.

    So, if you would like to have native support of the SCD then Sql Server does everything for, just do not touch these columns. If for the some special reasons you need to update these columns, then just do not use GENERATED ALWAYS columns and use DEFAULT constrains for that.

提交回复
热议问题