来自 C# 代码的 SQL Lead 和 Lag 函数 [英] SQL Lead and Lag functions from C# code
问题描述
是否可以使用 C# 中的 LEAD
或 LAG
SQL 函数?
Is it possible to use the LEAD
or LAG
SQL functions from C#?
我对方法的偏好是:
- Linq to SQL
- 实体框架
- 动态链接
- SQLFunctions 类
- 通过 SQLCommand 手动 TSQL
我知道可以通过方法 5 来完成,但是 1 到 4 呢?
I know it can be done via method 5, but what about 1 through 4?
推荐答案
查看 MoreLinq 项目(在 github 上):http://morelinq.github.io
Look into the MoreLinq project (on github): http://morelinq.github.io
There、Lead 和 Lag 作为扩展实现:
There, Lead and Lag are implemented as extensions:
public static IEnumerable<TResult> Lag<TSource, TResult>(
this IEnumerable<TSource> source,
int offset,
TSource defaultLagValue,
Func<TSource, TSource, TResult> resultSelector
)
参考:https://morelinq.github.io/2.0/ref/api/html/M_MoreLinq_MoreEnumerable_Lag__2_1.htm
这只是 Linq to Objects.因此,当应用于 SQL 数据源时,它将获取所有行,然后在数据库外进行计算.这不是 OP 所期望的.
This is Linq to Objects only. So when applied to an SQL data source, it would fetch all rows and then do the computation outside the database. This is not what the OP expects.
研究结果说不,这是不可能的";对于第 1、2、3 和 4 项:
Research results say "no, it is not possible" for items 1,2,3 and 4:
LEAD
和LAG
出现在 SQL Server 2012 中,但是最新版本的 Linq to SQL(框架 4.6.1)针对的最高版本的 SQL Server版本特定代码,是 2008:http://referencesource.microsoft.com/#System.Data.Linq/SqlClient/SqlProvider.cs,2fac3481a656764b- 实体框架:不,抱歉.
- MSDN 提示序列函数通常支持有限:https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/bb882656(v=vs.100)
- 没有暗示
SqlFunctions
会提供 Lead、Lag 或类似的东西:https://docs.microsoft.com/en-us/dotnet/api/system.data.objects.sqlclient.sqlfunctions?&view=netframework-4.8
LEAD
andLAG
came about in SQL Server 2012, but the highest version of SQL server that the newest version of Linq to SQL (Framework 4.6.1) targets with version specific code, is 2008: http://referencesource.microsoft.com/#System.Data.Linq/SqlClient/SqlProvider.cs,2fac3481a656764b- Entity framework: nope, sorry.
- MSDN hints that sequence functions generally have limited support: https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/bb882656(v=vs.100)
- There is no hint that
SqlFunctions
would provide Lead, Lag, or something similar: https://docs.microsoft.com/en-us/dotnet/api/system.data.objects.sqlclient.sqlfunctions?&view=netframework-4.8
这篇关于来自 C# 代码的 SQL Lead 和 Lag 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!