C#SqlConnection查询时态表

时间:2017-07-17 12:19:04

标签: c# sql-server sqlconnection temporal temporal-tables

我有一个时间表Employee,其中EmployeeHistory作为其历史记录表。

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

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

这会引发错误:

  

FOR

附近的语法不正确

那么,我们如何使用SqlConnection

在C#中查询时态表的历史数据

4 个答案:

答案 0 :(得分:2)

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

select * from Employee FOR SYSTEM_TIME ALL WHERE Id=15 

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

同时查看此相关帖子Why does the FOR Clause not work with an alias in SQL Server 2016 with temporal tables?

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

SELECT name, compatibility_level FROM sys.databases;

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

答案 3 :(得分:0)

如果你真的想使用别名,比如你的查询是否相当复杂&你想要更好的格式化,你可以使用CTE分两步完成:

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

select *
from _data as d

OR

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

select *
from _data as d
where d.Id=15 
相关问题