Saturday, September 2, 2017

Converting an Existing SQL Server Table to a Temporal Table

One of the very useful features added in SQL Server 2016 were temporal tables.  With a temporal table, SQL Server will automatically record a history of all changed data rows to a history table associated with the temporal table.  Further, SQL Server gives us some new syntax to be able to easily query what the data in the table looked like at any point in time or to show the entire history of a row in a table.  If you want more details, you can check out this earlier blog post I wrote on temporal tables.

However, what if we have an existing table in our database that we want to convert to a temporal table?  Lets take a look at how we do that.

For this example, lets assume that we have the following table that already exists in our database.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
CREATE TABLE Employees
(
    EmployeeId    INT          NOT NULL,
    FirstName     VARCHAR(20)  NOT NULL,
    LastName      VARCHAR(20)  NOT NULL,
    Email         VARCHAR(50)  NOT NULL,
    Phone         VARCHAR(20)  NULL,
    CONSTRAINT PK_Employees
        PRIMARY KEY (EmployeeId)
);


To convert this table to a temporal table, it is a two step process.  The first step is that we need to add our ValidFrom/ValidTo columns to the table to represent when the row was active in the table.  So we can run the following statement to do this.


1
2
3
4
5
6
ALTER TABLE Employees ADD 
    ValidFrom DATETIME2(3) GENERATED ALWAYS AS ROW START 
        NOT NULL DEFAULT '1900-01-01 00:00:00.000',
    ValidTo   DATETIME2(3)  GENERATED ALWAYS AS ROW END 
        NOT NULL DEFAULT '9999-12-31 23:59:59.999',
    PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);

Here we are adding the two columns needed for when the row is valid and the PERIOD that is required by a temporal table.  Some things to note:

  • We could name the columns ValidFrom and ValidTo anything that we want to, these are just the names that I chose.
  • These columns must be of a DATETIME2 data type.  In this case, I am using DATETIME2(3) to go down to millisecond precision.
  • We need to provide default values for these columns in order to populate the existing rows on the table.  For my ValidFrom I chose 1/1/1900 as a default starting date.  The ending date for the rows in ValidTo column must be the maximum date/time value for our data type, so in this case, 12/31/999 at 23:59:99.999.
  • Otherwise, the syntax for the columns look much like the syntax for the columns in the CREATE TABLE statement.
Then, we need to run step 2 of the process:


1
2
ALTER TABLE Employees			
    SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.EmployeesHistory));

Here, we turn on SYSTEM_VERSIONING for the table so the ValidFrom and ValidTo dates will be auto-generated and define the name of the history table to use.

And that is all there is to it.  Now, your table has been converted to a temporal table and any changes to your table will be tracked in the history table.  






6 comments:

  1. Ok, that's wayyy too complicated for me ;) Luckily, my software developer (in an outsourcing service) doesn't require me to engage in any kind of IT activities. If you're looking for a trust-worthy software developing company, let me know or just check here.

    ReplyDelete
  2. I think that is actually a very useful blog post about SQL server and throws light on some of its very useful aspects.

    SQL Server Load Soap API

    ReplyDelete
  3. GET  ACCESS TO ANY CELLPHONE REMOTELYHACK ANY WHATSAPP  ACCOUNT HACK ANY INSTAGRAM  ACCOUNT  HACK ANY FACEBOOK ACCOUNTUsing SS7
    GET ALL MONEY ADDERS SOFTWARE HERE WITH PROOF  
    PAYPAL MONEY ADDERPAYONEER MONEY ADDERBITCOIN MONEY ADDER
    SKRILL MONEY ADDER
    Western Union bug 
    NETELLER ADDER

    DEBIT CARD LOADER
    BANK ACCOUNT LOADER
    CREDIT CARD LOADER
    CLONE CARDS
    HACK ANY GMAIL ACCOUNTLinkedIn email and password hacking
    SS7 SOFTWARE AVAILABLESerious inquiries only
    contact me : putro9111@gmail.comTelegram:   https://t.me/Hackord247Phone:   +1 (912) 805-7496https://makemoneywithputro.wordpress.com/
     HACK N'IMPORTE QUEL COMPTE WHATSAPP
     HACKER TOUT COMPTE INSTAGRAM
     HACK N'IMPORTE QUEL COMPTE FACEBOOK
     OBTENEZ TOUS LES LOGICIELS AJOUT D'ARGENT AVEC LA PREUVE
     AJOUT D'ARGENT PAYPAL
     AJOUT D'ARGENT PAYONEER
     BITCOIN MINER BOTAJOUT D'ARGENT DE SKRILLBug de Western UnionNETELLER ADDER
     CHARGEUR DE CARTE DE DÉBIT
     CHARGEUR DE COMPTE BANCAIRE
     CHARGEUR DE CARTE DE CRÉDIT
     CARTES CLONE
     HACKER TOUT COMPTE GMAIL Piratage d'e-mails et de mots de passe LinkedIn
     LOGICIEL SS7 DISPONIBLE
     Enquêtes sérieuses uniquement
     contactez-moi: putro9111@gmail.com
     Télégramme: https://t.me/Hackord247
     Téléphone: +1 (912) 805-7496
     https://makemoneywithputro.wordpress.com/

    私に連絡してください:putro9111@gmail.com
     WHATSAPPのアカウントをハック
     インスタグラムアカウントをハックする
     Facebookアカウントをハック

     証拠のあるすべてのマネーアダーソフトウェアをここで入手する

     PAYPAL MONEY ADDER

     PAYONEER MONEY ADDER
     ビットコインマイナーボット
     SKRILL MONEY ADDER
     ウエスタンユニオンバグ
     NETELLER ADDER
     デビットカードローダー
     銀行口座ローダー
     クレジットカードローダー
     クローンカード
     Gmailアカウントをハック LinkedInのメールとパスワードのハッキング
     利用可能なSS7ソフトウェア
     深刻な問い合わせのみ
     私に連絡してください:putro9111@gmail.com
     電報:https://t.me/Hackord247
     電話:+1(912)805-7496
     https://makemoneywithputro.wordpress.com/



     
     拥有任何WHATSAPP帐户
     拥有任何INSTAGRAM帐户
     拥有任何FACEBOOK帐户

     在此处获取带有证明的所有货币添加软件

     贝宝付款
     收款人付款人
     比特币矿工机器人
     速效货币加法器
     西联汇款错误
     NETELLER ADDER
     借记卡装载器
     银行帐户装载程序
     信用卡装载机
     克隆卡
     拥有任何GMAIL帐户 LinkedIn电子邮件和密码黑客
     提供SS7软件
     仅认真查询
     与我联系:putro9111@gmail.com
     电报:https://t.me/Hackord247
     电话:+1(912)805-7496
     https://makemoneywithputro.wordpress.com/


     Взломать любой аккаунт
     Взломать любой аккаунт INSTAGRAM
     Взломать любой аккаунт в FACEBOOK
     ПОЛУЧИТЕ ВСЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ДЕНЕГ ДОБАВЛЯЕТ СЮДА
     ПОДСЧЕТ ДЕНЕГ PAYPAL
     PAYONEER MOND ADDER
     BITCOIN MINER BOT
     SKRILL MOND ADDER
     Ошибка Western Union
     NETELLER ADDER
     ПОГРУЗЧИК ДЕБЕТНОЙ КАРТЫ
     ПОГРУЗЧИК БАНКОВСКОГО СЧЕТА
     ПОГРУЗЧИК КРЕДИТНОЙ КАРТЫ
     КЛОННЫЕ КАРТЫ
     Взломать любой аккаунт GMAIL LinkedIn взлом электронной почты и паролей
     ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ SS7 В НАЛИЧИИ
     Только серьезные запросы
     свяжитесь со мной: putro9111@gmail.com
     Telegram: https://t.me/Hackord247
     Телефон: +1 (912) 805-7496
     https://makemoneywithputro.wordpress.com/
     
     HACKEN SIE JEDES WHATSAPP-KONTO
     HACKEN SIE JEDES INSTAGRAM-KONTO
     HACK JEDES FACEBOOK-KONTO
     HIER ERHALTEN SIE ALLE GELDADDERS-SOFTWARE MIT BEWEIS
     PAYPAL GELD ADDER
     PAYONEER GELDADDER
     BITCOIN MINER BOT
     SKRILL GELDADDER
     Western Union Bug
     NETELLER ADDER
     DEBIT CARD LOADER
     BANKKONTO-LADER
     KREDITKARTENLADER
     KLONKARTEN
     HACK JEDES GMAIL-KONTO LinkedIn E-Mail- und Passwort-Hacking
     SS7 SOFTWARE VERFÜGBAR
     Nur ernsthafte Anfragen
     Kontaktieren Sie mich: putro9111@gmail.com
     Telegramm: https://t.me/Hackord247
     Telefon: +1 (912) 805-7496
     https://makemoneywithputro.wordpress.com/

    ReplyDelete
  4. Nice Post !
    Are you unable to work on QuickBooks software? If yes, then do call us at QuickBooks Customer Service Number 1-877-948-5867 and get sure-shot solutions to troubleshoot all the issues of QuickBooks.

    ReplyDelete
  5. This is pravali from bangalore looking for sap training but wich module is best Rise With SAP Implementation

    ReplyDelete
  6. good info and we are giving some training on sap coerce and jobSAP Cloud For Analytics

    ReplyDelete