I'm having a problem updating rows in a temporal history table in MS SQL Server 2016.
From the documentation, the steps that should be needed are as follows:
I tried creating a procedure that does this, but got this error:
Msg 13561, Level 16, State 1, Line 23 Cannot update rows in a temporal history table 'db.dbo.FooHistory'.
Here is my SQL:
CREATE TABLE Foo(
id int primary key not null
, title nvarchar(50) not null
, startTime datetime2 GENERATED ALWAYS AS ROW START NOT NULL
, endTime datetime2 GENERATED ALWAYS AS ROW END NOT NULL
, PERIOD FOR SYSTEM_TIME (startTime, endTime) )
ALTER TABLE Foo
SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.FooHistory));
GO
CREATE PROCEDURE [dbo].[UpdateFooHistory] AS
BEGIN
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
ALTER TABLE dbo.Foo SET (SYSTEM_VERSIONING = OFF);
UPDATE dbo.FooHistory
SET title = 'Foo';
ALTER TABLE dbo.Foo SET (SYSTEM_VERSIONING = ON (
HISTORY_TABLE = dbo.FooHistory,
DATA_CONSISTENCY_CHECK = ON
));
COMMIT TRANSACTION
RETURN 0
END
GO
It seems like SQL Server is checking if a table is temporal at "compile time" rather than at runtime. Is this true? Is there a way to work around it?
Yes. The data "in" a view has no existence independent from the tables that make up the view. The view is, in essence, a stored SELECT statement that masquerades as a table. The data is stored in the original tables and only "assembled" into the view when you want to look at it.
To delete data from a system-period temporal table, use the DELETE FROM statement. For example, the owner of policy B345 decides to cancel insurance coverage. The data was deleted on September 1, 2011 (2011-09-01) from the table that was updated in the Updating data in a system-period temporal table topic.
To get the last updated record in SQL Server: We can write trigger (which automatically fires) i.e. whenever there is a change (update) that occurs on a row, the “lastupdatedby” column value should get updated by the current timestamp.
Change the UPDATE statement to this, and it will let you create the procedure:
EXEC(N'UPDATE dbo.FooHistory SET title = ''Foo''');
With SQL Server 2019 it does not work any more (neither with exec nor with sp_executesql). You need to use a workaround.
In order to prevent any other user to change something while the versioning is off first start a serializable transaction:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
Temporarily disable SYSTEM_VERSIONING on the table:
ALTER TABLE Foo SET (SYSTEM_VERSIONING = OFF);
Modify the history table:
UPDATE dbo.FooHistory SET title = 'Foo';
Re-enable the versioning:
ALTER TABLE Foo SET (SYSTEM_VERSIONING = ON ( HISTORY_TABLE = dbo.FooHistory, DATA_CONSISTENCY_CHECK = ON));
Commit the transaction:
COMMIT TRANSACTION;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With