C# SqlConnection 查询时态表

C# SqlConnection Querying Temporal tables

我有一个时间 table Employee,其历史记录 EmployeeHistory table。

在 C# 中,我使用 SqlConnection 从 SQL 服务器查询员工的整个历史记录的数据。

var data = Conn.ExecuteReader("select * from Employee e FOR SYSTEM_TIME ALL WHERE e.Id=15");

这会引发错误:

Incorrect syntax near FOR

那么,我们如何使用 SqlConnection 在 C# 中查询时间 table 的历史数据?

问题是您正在使用 table 别名 e,所以出现错误。不要认为你可以使用 table 别名。将其更改为

select * from Employee FOR SYSTEM_TIME ALL WHERE Id=15 

如果你查看文档 Querying Data in a System-Versioned Temporal Table (要么) Temporal Tables 您会看到语法根本没有显示 table 别名的使用。相反,您将不得不使用整个 table 名称。

也请参阅此相关内容 post Why does the FOR Clause not work with an alias in SQL Server 2016 with temporal tables?

SELECT name, compatibility_level FROM sys.databases;

仅当您的数据库级别为 130 或更高时才有效

如果您真的想使用别名,比如如果您的查询非常复杂并且您想要更好的格式,您可以使用 CTE 分两步完成此操作:

with _data as
(
    select * 
    from Employee 
    for system_time all 
    where Id=15 
)

select *
from _data as d

with _data as
(
    select * 
    from Employee 
    for system_time all 
)

select *
from _data as d
where d.Id=15 

澄清一下,如果您需要别名和 FOR SYSTEM_TIME,请使用以下语法:

var data = Conn.ExecuteReader("select * from Employee FOR SYSTEM_TIME ALL e WHERE e.Id=15");