-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy path06-query-temporal-data-basic.sql
71 lines (58 loc) · 1.67 KB
/
06-query-temporal-data-basic.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
-- No order at all
select * from dbo.OrderInfo for system_time as of '2016-07-03 15:00:00'
go
-- Received
select * from dbo.OrderInfo for system_time as of '2016-09-03 10:00:00'
go
-- In-Progress
declare @d datetime2 = dateadd(day, -7, sysutcdatetime());
select *, @d as as_of_date from dbo.OrderInfo for system_time as of @d;
go
-- Now create a new temporal table and insert some customer data
create table dbo.Customer
(
[customer_id] varchar(10) not null primary key,
[address] nvarchar(100) not null,
[city] nvarchar(100) not null,
[region] nvarchar(100) not null,
[country] nvarchar(100) not null,
[valid_from] datetime2 not null,
[valid_to] datetime2 not null
)
go
insert into dbo.Customer values
('DM', '1st Redmond Way', 'Redmond', 'WA', 'United States', '20160801', '9999-12-31 23:59:59.9999999')
go
alter table dbo.Customer
add period for system_time ([valid_from], [valid_to])
go
alter table dbo.Customer
set (system_versioning = on (history_table = dbo.CustomerHistory))
;
alter table dbo.Customer
set ( system_versioning = off )
go
insert into dbo.CustomerHistory values
('DM', 'Via Monte Grappa 20', 'Milano', 'Lombardia', 'Italy', '20010101', '20160801')
go
alter table dbo.Customer
set (system_versioning = on (history_table = dbo.CustomerHistory, data_consistency_check = on))
;
select * from dbo.Customer for system_time all
go
create view dbo.FlatOrderInfo
as
select
c.[address],
c.[city],
c.[region],
o.*
from
dbo.[OrderInfo] o
inner join
dbo.[Customer] c on [c].[customer_id] = [o].[customer_id]
go
-- Current view
select * from dbo.[FlatOrderInfo]
-- "Magic"! :)
select * from dbo.[FlatOrderInfo] for system_time as of '20160701'