Sql server 过程执行查询需要很长时间

Sql server 过程执行查询需要很长时间,sql-server,sql-server-2008,Sql Server,Sql Server 2008,我有以下用于SQL Server的SP。奇怪的是,SP在执行查询时有奇怪的行为 Select @max_backup_session_time = Max(MachineStat.BackupSessionTime) from MachineStat where MachineStat.MachineID = @machine_id; 如果MachineStat表中有与@machine\u id相关的行,则需要1秒,但如果没有与@machine\u id相关的行,则需要半分钟以上的时间

我有以下用于SQL Server的SP。奇怪的是,SP在执行查询时有奇怪的行为

Select @max_backup_session_time = Max(MachineStat.BackupSessionTime) from MachineStat     where MachineStat.MachineID = @machine_id;
如果MachineStat表中有与@machine\u id相关的行,则需要1秒,但如果没有与@machine\u id相关的行,则需要半分钟以上的时间执行。有人能帮我理解这一点吗

SET NOCOUNT ON;

DECLARE @MachineStatsMId TABLE (
  MachineId         INT NULL,
  BackupSessiontime BIGINT NULL,
  MachineGroupName  NVARCHAR(128) NULL )
DECLARE @machine_id AS INT;
DECLARE @Machine_group_id AS INT;
DECLARE @machine_group_name AS NVARCHAR(128);
DECLARE @max_backup_session_time AS BIGINT;

SET @machine_id = 0;
SET @Machine_group_id = 0;
SET @machine_group_name = '';

DECLARE MachinesCursor CURSOR FOR
  SELECT m.MachineId,
         m.MachineGroupId,
         mg.MachineGroupName
  FROM   Machines m,
         MachineGroups mg
  WHERE  m.MachineGroupId = mg.MachineGroupId;

OPEN MachinesCursor;

FETCH NEXT FROM MachinesCursor INTO @machine_id, @machine_group_id, @machine_group_name;

WHILE @@FETCH_STATUS = 0
  BEGIN
      SELECT @max_backup_session_time = Max(MachineStat.BackupSessionTime)
      FROM   MachineStat
      WHERE  MachineStat.MachineID = @machine_id;

      INSERT INTO @MachineStatsMId
      VALUES      (@machine_id,
                   @max_backup_session_time,
                   @machine_group_name);

      FETCH NEXT FROM MachinesCursor INTO @machine_id, @machine_group_id, @machine_group_name;
  END;

SELECT *
FROM   @MachineStatsMId;

CLOSE MachinesCursor;

DEALLOCATE MachinesCursor;
GO

这里有一个替代版本,它完全避免使用游标和表变量,使用适当的(现代的)联接和模式前缀,并且运行速度应该比现有的快得多。如果在某些场景中仍然运行缓慢,请发布该场景的实际执行计划以及快速场景的实际执行计划

ALTER PROCEDURE dbo.procname
AS
BEGIN
  SET NOCOUNT ON;

  SELECT 
    m.MachineId, 
    BackupSessionTime = MAX(ms.BackupSessionTime), 
    mg.MachineGroupName
  FROM dbo.Machines AS m
  INNER JOIN dbo.MachineGroups AS mg 
    ON m.MachineGroupId = mg.MachineGroupId
  INNER JOIN dbo.MachineStat AS ms -- you may want LEFT OUTER JOIN here, not sure
    ON m.MachineId = ms.MachineID
  GROUP BY m.MachineID, mg.MachineGroupName;
END
GO

你为什么用光标?为什么要使用旧式联接?如果必须使用光标,而不是使用光标执行更新或双向移动,请将其设置为本地快进。(不过,实际上并不需要光标。)