我的网页上有一个小搜索功能。
IF LEN(@firstName) < 1 OR @firstName IS NULL
set @firstName = '%'
IF LEN(@lastName) < 1 OR @lastName IS NULL
set @lastName = '%'
IF LEN(@carrierId) < 1 OR @carrierId IS NULL
set @carrierId = '%'
IF LEN(@worksheetId) < 1 OR @worksheetId IS NULL
set @worksheetId = '%'
SELECT TOP 1000 m.[Guid], m.WorksheetID, d.FirstName, d.LastName, m.VersionNum FROM Main m
INNER JOIN utl_Driver d ON m.DriverID = d.DriverID
WHERE d.FirstName LIKE @firstName
AND d.LastName LIKE @lastName
AND d.CarrierID LIKE @carrierId
AND m.WorksheetID LIKE @worksheetId
AND m.Deleted = 0
AND d.VersionNum = (SELECT MAX(VersionNum)
FROM Main B WHERE b.WorksheetID = m.WorksheetID)
ORDER BY m.DateTimeStart DESC;
在SQL Server Management Studio中快速闪电,但在我的ASP.Net应用程序调用存储过程时表现奇怪。通过LastName搜索通常很快,但FirstName或WorksheetID超时。此外,删除'm.Deleted = 0'检查会使所有查询执行得非常快,但我显然需要检查。有什么建议吗?
答案 0 :(得分:1)
此查询永远不会预先形成。你正在4个不同的领域进行表扫描。 我也没有在查询中看到任何分页,这意味着返回所有结果。这将是大量数据的问题。
介绍webforms,现在你有了viewstate。网格/列表视图将整个结果集存储在viewstate中(即使您启用了客户端分页)。
这是我看到的3个主要瓶颈。 1.由于“喜欢”运算符导致查询性能不佳 2.结果集可能太大 3. webforms查看状态
答案 1 :(得分:1)
请您尝试如下:感谢您的时间。
DECLARE @whereCondition NVARCHAR(1000)
SET @whereCondition = ' WHERE 1 = 1 '
IF @firstName <> '' AND @firstName IS NOT NULL
SET @whereCondition = @whereCondition + ' AND d.FirstName LIKE ''' + @firstName + ''''
IF @lastName <> '' AND @lastName IS NOT NULL
SET @whereCondition = @whereCondition + ' AND d.LastName LIKE ''' + @lastName + ''''
IF @carrierId <> '' AND @carrierId<> 0 AND @carrierId IS NOT NULL
SET @whereCondition = @whereCondition + ' AND d.CarrierID LIKE ''' + @carrierId + ''''
IF @worksheetId <> '' AND @worksheetId<> 0 AND @worksheetId IS NOT NULL
SET @whereCondition = @whereCondition + ' AND m.WorksheetID LIKE ''' + @worksheetId + ''''
SET @whereCondition = @whereCondition + ' AND m.Deleted = 0'
SET @whereCondition = @whereCondition + ' AND d.VersionNum = (SELECT MAX(VersionNum)
FROM Main B WHERE b.WorksheetID = m.WorksheetID) '
EXEC('SELECT TOP 1000 m.[Guid], m.WorksheetID, d.FirstName, d.LastName, m.VersionNum FROM Main m
INNER JOIN utl_Driver d ON m.DriverID = d.DriverID '
+ @whereCondition +
' ORDER BY m.DateTimeStart DESC; ' )