过程需要很长时间才能执行查询

时间:2012-08-10 14:32:30

标签: 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_id相关的行,但如果没有@machine_id的行,则需要1秒钟,因此执行时间超过半分钟。有人可以帮我理解这一点。

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

1 个答案:

答案 0 :(得分:1)

这是一个替代版本,它完全避免了游标和表变量,使用了正确的(现代)连接和模式前缀,并且应该比你拥有的更快。如果在某些情况下仍然运行缓慢,请发布该方案的实际执行计划以及快速方案的实际执行计划。

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