【发布时间】:2017-01-09 15:31:26
【问题描述】:
我目前正在使用带有 Linq 的 SQL Server 2008 R2 和 ASP.Net
在服务器 1 上
我们有一个包含大约一百万条记录的地址信息表的数据库。
在服务器 2 上
我有一个包含大约 1/2 百万条记录的客户表,其中包含一个 AddressID
我创建了一个同义词来链接到地址表的服务器 1。并创建了一个视图以在 Server 2 中将两个表链接在一起。
一个处理数据分页的存储过程,以便它返回一个包含 20 条记录的页面,还尝试将 RowNumber 添加到实际视图中,但没有提高速度
CREATE PROCEDURE [dbo].[GetCustomerAddressesByPage]
(
@pageIndex int,
@pageSize int,
@totalRows int output
)
AS
BEGIN
DECLARE @startRowIndex int
DECLARE @endRowIndex int
SET @startRowIndex = (@pageIndex * @pageSize) + 1;
SET @endRowIndex = (@pageIndex + 1) * @pageSize;
--SELECT * FROM
-- (SELECT ROW_NUMBER() OVER (ORDER BY CustomerID) AS RowNumber,*
-- FROM View_CustomersAddress) xx
--WHERE RowNumber >= @startRowIndex AND RowNumber <= @endRowIndex
SELECT *
FROM View_CustomersAddress
WHERE RowNum >= @startRowIndex AND RowNum <= @endRowIndex
SELECT @totalRows = COUNT(*) FROM View_CustomersAddress
END
这会在 2 秒内返回数据,但要处理页数,我还需要总行数,并且以下代码需要另外 20 秒左右才能完成
SELECT @totalRows = COUNT(CustomerID) FROM View_CustomersAddress
服务器代码如下,用于在 gridview 中填充数据
public IQueryable<GetCustomerAddressLinesByPageResult2> GetAddress(int startRowIndex, int maximumRows)
{
var data = dbContext.GetCustomerAddressLinesByPage(startRowIndex, maximumRows);
return data;
}
视图不包含任何索引,因为您不能使用同义词,因此我目前将总行数存储在我的 asp.net 程序中的视图状态中,因此初始加载需要 25 秒以上,但分页没问题。
有没有什么方法可以提高 count() 的性能,或者可能是另一种不使用 count() 的方法,这是我没有想到的。
只是为了澄清
服务器 1 上的地址表有一个主键 AddressID 并且是唯一的
服务器 2 上的客户表有一个主键 CustomerID,并且是唯一的
由于服务器 1 和服务器 2 之间的同义词,View_CustomersAddress 没有任何索引
【问题讨论】:
-
基础表中 CustomerId 的索引是什么?另外,您真的希望 count(customerid) 或 count(distinct customerid) 或 customerId 在此表中是唯一的吗?
-
对不起,CustomerID是主键,是唯一的
-
看看他的帖子。或许能帮到你stackoverflow.com/a/6069288/3877877
-
我之前尝试过使用 sys.dm_db_partition_stats 但这仅适用于表,而不适用于视图
-
这对你没有帮助,但我想知道你为什么要做 count(CustomerID) 而不仅仅是 Count(1) 或 Count(*) ?
标签: c# asp.net sql-server linq