C# SqlConnection Querying Temporal tables

一曲冷凌霜 提交于 2019-12-11 12:46:49

问题


I have a temporal table Employee with EmployeeHistory as its history table.

In C#, I am using SqlConnection to query the data from SQL Server for the entire history of an employee.

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

This throws the error:

Incorrect syntax near FOR

So, how do we query history data for a temporal table in C# using SqlConnection?


回答1:


Problem is you are using table alias e and so the error. Don't think you can use table alias. change it to

select * from Employee FOR SYSTEM_TIME ALL WHERE Id=15 

If you check the documentation Querying Data in a System-Versioned Temporal Table (OR) Temporal Tables you will see that the syntax doesn't show the use of table alias at all. Rather you will have to use the entire table name.

See this related post as well Why does the FOR Clause not work with an alias in SQL Server 2016 with temporal tables?




回答2:


Just to clarify, if you need aliases and FOR SYSTEM_TIME, use following syntax:

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



回答3:


SELECT name, compatibility_level FROM sys.databases;

It work only if your database is level 130 or more




回答4:


If u really want to use an alias, like if your query if quite complicated & u want better formatting, you can do this in 2 steps, using a 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 


来源:https://stackoverflow.com/questions/45144148/c-sharp-sqlconnection-querying-temporal-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!