SQL Temporal Tables — Gotcha!!!1 min read

Hello, again reader…

Today, I will discuss a gotcha I ran across with SQL Server Temporal Tables. In my day-to-day environment, we do not use Temporal Tables widely.  However, a few are in use, and a few are coming down the pipeline for new projects.

If you have not heard of Temporal Tables, you can review the information from Microsoft. If you are interested in trying these out, they did not show up on the SQL Server scene until 2016.

This past week I was asked to promote schema and data from a new development database to a testing database.  The steps given were the following.

  1. Compare schema from dev to test for a specific schema
  2. Truncate data in all tables in the test for a specific schema
  3. Migrate all data in dev to test for a specific schema

Look and sound pretty straightforward.  I open RedGate SQL Compare enter the source and destination systems, and bam, number one is done.

Next, let me run the truncate script on the test database.

Uh oh, a red error message is never good.

It appears that a truncate table command is not compatible with Temporal Tables. So after a bit of research, I found you can run the following code to get past the issue.

Let me explain what we have going on here. First, we have to turn off temporal system versioning on the table. Then we can truncate the table as we tried initially.  Finally, we turn system versioning back on for the table.

It is not as straightforward as a standard table, but there are ways to accomplish the truncate command.

Don’t get me started about foreign keys. 🤣🤣🤣


4 Replies to “SQL Temporal Tables — Gotcha!!!1 min read

  1. I’ve also found out (the hard way) that you have to name your temporal table, if you do not want to take the Microsoft default name.

  2. Also, you probably want to truncate the history table as well as the main table before turning versioning back on.

Leave a Reply

Your email address will not be published. Required fields are marked *