4

最后更新

经过大量测试后,我意识到如果我在 SQL 2000 和 SQL 2005 上对同一个数据集(在本例中为 Northwind)表运行相同的查询,我会得到两个不同的结果。在 SQL 2000 上,我得到了问题中的错误。在 SQL 2005 上,它成功了。

所以我得出结论,linqpad 生成的查询在 sql 2000 上不起作用。要重现这一点,请运行:

OrderDetails
    .GroupBy(x=>x.ProductID)
    .Select(x=>new {product_id = x.Key, max_quantity = x.OrderByDescending(y=>y.UnitPrice).FirstOrDefault().Quantity}).Dump();

在 sql 2000 中的 Northwind DB 上。 sql 翻译是:

SELECT [t1].[ProductID] AS [product_id], (
    SELECT [t3].[Quantity]
    FROM (
        SELECT TOP 1 [t2].[Quantity]
        FROM [OrderDetails] AS [t2]
        WHERE [t1].[ProductID] = [t2].[ProductID]
        ORDER BY [t2].[UnitPrice] DESC
        ) AS [t3]
    ) AS [max_quantity]
FROM (
    SELECT [t0].[ProductID]
    FROM [OrderDetails] AS [t0]
    GROUP BY [t0].[ProductID]
    ) AS [t1]

原始问题

我有以下查询:

ATable
.GroupBy(x=> new {FieldA = x.FieldAID, FieldB = x.FieldBID, FieldC = x.FieldCID})
.Select(x=>new {FieldA = x.Key.FieldA, ..., last_seen = x.OrderByDescending(y=>y.Timestamp).FirstOrDefault().Timestamp})

结果是:

SqlException: Invalid column name 'FieldAID' x 5
SqlException: Invalid column name 'FieldBID' x 5
SqlException: Invalid column name 'FieldCID' x 1

我已经确定它与对 Timestamp 的最后一个查询有关,因为它有效:

ATable
.GroupBy(x=> new {FieldA = x.FieldAID, FieldB = x.FieldBID, FieldC = x.FieldCID})
.Select(x=>new {FieldA = x.Key.FieldA, ...,  last_seen = x.OrderByDescending(y=>y.Timestamp).FirstOrDefault()})

查询已被简化。目的是按一组变量进行分组,然后显示该分组最后一次在 db 中发生的时间。

我正在使用 Linqpad 4 生成这些结果,因此 Timestamp 给了我一个字符串,而 FirstOrDefault 给了我不理想的整个对象。

更新
在进一步的测试中,我注意到 SQLException 的数量和类型与 groupby 子句中创建的类有关。所以,

ATable
.GroupBy(x=> new {FieldA = x.FieldAID})
.Select(x=>new {FieldA = x.Key.FieldA, last_seen = x.OrderByDescending(y=>y.Timestamp).FirstOrDefault()})

结果是

SqlException: Invalid column name 'FieldAID' x 5
4

1 回答 1

0

You should use the SQL profiler to check if the SQL generated against the 2 databases is different.

We have only had two problems where something ran on SQL Server 2005 but not on SQL Server 2000. In both cases it was due to the lack of support for Multiple Active Result Sets (MARS) in SQL Server 2000. In one case it led to locking in the database, in the other case it led to a reduction of performance.

于 2012-03-14T18:55:53.260 回答