来自 C# 代码的 SQL Lead 和 Lag 函数 [英] SQL Lead and Lag functions from C# code

查看:24
本文介绍了来自 C# 代码的 SQL Lead 和 Lag 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 C# 中的 LEADLAG SQL 函数?

Is it possible to use the LEAD or LAG SQL functions from C#?

我对方法的偏好是:

  1. Linq to SQL
  2. 实体框架
  3. 动态链接
  4. SQLFunctions 类
  5. 通过 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 and LAG 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆