我有一个从表中检索简单数据的存储过程。一年多来它工作得很好,但几天来选择数据需要 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
什么是最好的解决方案?