I have the following SP for SQL Server. Strangely the SP has weired behaviour when executing the query
Select @max_backup_session_time = Max(MachineStat.BackupSessionTime) from MachineStat where MachineStat.MachineID = @machine_id;
It takes 1 second if the MachineStat table has rows pertaining to @machine_id but if there are no rows for a @machine_id then it takes more than half a minute to execute. Can someone please help me understand this.
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
Here is an alternate version that avoids a cursor and table variable entirely, uses proper (modern) joins and schema prefixes, and should run a lot quicker than what you have. If it still runs slow in certain scenarios, please post the actual execution plan for that scenario as well as an actual execution plan for the fast scenario.