我有一个存储过程,可以从表中检索简单数据。一年多以来它工作得很好,但是几天内选择数据的时间超过30秒。有时它甚至没有在用户界面上显示任何内容。
如果我在SQL Server Management Studio中执行相同的存储过程,则执行需要2-3秒。我试图重新编译正在使用的表和过程,并增加了超时。但它没有帮助,我需要你的建议。
以下是我的存储过程:
ALTER PROCEDURE [dbo].[sp_Monitoring_ver2]
@AgentID int = NULL
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
select ROW_NUMBER() OVER(order by AgentFullName ASC) as CodeID, res.*, DATEDIFF(mi, stsdate, getdate()) as MinFromLastSignal, DATEDIFF(MI, LastPaymentDateTime, getdate()) as MinFromLastPayment
from
(
SELECT s.AgentID, a.name+' '+a.surname as TerminalFullName, a.loginName,
s.KioskStatus, s.StsDate, s.TotalMoney, s.AmountMoney, s.MoneyInside, s.Version, s.PrinterErrorCode, s.ValidatorErrorCode,
(select top(1) StatusDateTime from Payment where AgentID = s.AgentID order by PaymentID desc) as LastPaymentDateTime,
prt.errtxt as PrinterErrorText, val.errtxt as ValidatorErrorText,
s.IPAddress,
b.AgentID as ParentID, b.[name]+' '+b.surname AS AgentFullName
,(SELECT TOP 1 i.RegDate FROM dbo.InkasaiyaOfTerm i WHERE i.AgentID=s.AgentID order by i.ID DESC) AS LastCollectionDate
,(SELECT TOP 1 i.Kol FROM dbo.InkasaiyaOfTerm i WHERE i.AgentID=s.AgentID order by i.ID DESC) AS LastCollectionQuantity
,(SELECT TOP 1 i.Summa FROM dbo.InkasaiyaOfTerm i WHERE i.AgentID=s.AgentID order by i.ID DESC) AS LastCollectionAmount
FROM StatusTerminal_ver2 s
INNER JOIN ErrorCodeTerminal prt ON s.PrinterErrorCode = prt.ecode
INNER JOIN ErrorCodeTerminal val ON s.ValidatorErrorCode = val.ecode
INNER JOIN Agents a ON s.AgentID=a.AgentID
INNER JOIN Agents b ON a.parentID=b.AgentID
where s.AgentID IN (select AgentID FROM Agents WHERE hrccrt LIKE '%.'+CAST(@AgentID as varchar(10))+'.%' and agentType=2)
and DATEDIFF(DAY, StsDate, GETDATE())<7
) as res
order by AgentFullName ASC
END
最佳解决方案是什么?
答案 0 :(得分:0)
在开头的存储过程中设置:
设置ARITHABORT ON
如果它没有任何区别,那么导致我的参数嗅探。 sql server已根据您传递的第一个参数编译了查询并生成了执行计划。该计划可能对其他参数不利。您可以使用optimize for子句。