SQL Server 2005查询的性能

Chr*_*n V 4 sql sql-server sql-server-2005

--------------------这需要4秒才能执行(有2000 000行)为什么?---------------- -----

DECLARE @AccountId INT 
DECLARE @Max INT 
DECLARE @MailingListId INT 

SET @AccountId = 6730
SET @Max = 2000
SET @MailingListId = 82924

SELECT TOP (@Max) anp_Subscriber.Id , Name, Email 
FROM anp_Subscription WITH(NOLOCK) 
  INNER JOIN anp_Subscriber WITH(NOLOCK) 
    ON anp_Subscriber.Id = anp_Subscription.SubscriberId
WHERE [MailingListId] = @MailingListId 
  AND Name LIKE '%joe%' 
  AND [AccountID] = @AccountId
Run Code Online (Sandbox Code Playgroud)

---------------------这需要<1秒才能执行(有2000 000行)---------------- -------

SELECT TOP 2000 anp_Subscriber.Id ,Name, Email 
FROM anp_Subscription WITH(NOLOCK) 
  INNER JOIN anp_Subscriber WITH(NOLOCK)
    ON anp_Subscriber.Id = anp_Subscription.SubscriberId
WHERE [MailingListId] = 82924 
  AND Name LIKE '%joe%' 
  AND [AccountID] = 6730
Run Code Online (Sandbox Code Playgroud)

为什么执行时间有差异?我想在顶部使用查询.我可以做任何优化吗?

提前致谢!/基督教

Mar*_*ith 6

添加OPTION (RECOMPILE)到查询的末尾.

SQL Server不会"嗅探"变量的值,因此您将根据猜测的统计信息获取计划,而不是根据实际变量值进行定制.