Hi i wounder if anyone has any tips on how i should optimize this Query?
DECLARE @RowsToProcess int
DECLARE @CurrentRow int
DECLARE @SelectCol1 int
declare @dateNow datetime
declare @macAdress varchar(100);
declare @port varchar(100);
declare @switchName varchar(100);
declare @vlan varchar(100);
declare @changedmacAdress varchar(100);
declare @changedvlan varchar(100);
DECLARE @table1 TABLE (RowID int not null primary key identity(1,1), col1 int,
[macAdress] [varchar](255) NULL,
[portName] [varchar](255) NULL,
[switchName] [varchar](255) NULL,
[vlan] [varchar](255) NULL)
INSERT into @table1 SELECT id,macAdress,portName,switchName,vlan FROM ForwardDatabase
SET @RowsToProcess=@@ROWCOUNT
select @dateNow = getdate()
SET @CurrentRow=0
WHILE @CurrentRow<@RowsToProcess
BEGIN
SET @CurrentRow=@CurrentRow+1
SET @macAdress = null;
SET @port = null;
SET @switchName = null;
SET @vlan = null;
SET @changedmacAdress = null;
SET @changedvlan = null;
SELECT
@SelectCol1=col1,@macAdress=macAdress,@port=portName,@switchName=switchName,@vlan=vlan
FROM @table1
WHERE RowID=@CurrentRow
select @macAdress=macAdress,@port=portName,@switchName=switchName,@vlan=vlan from @table1 where RowID = @SelectCol1
select @changedmacAdress=macAdress,@changedvlan=vlan from HistoryForwardDatabase where macAdress= @macAdress and vlan = @vlan and portName = @port and switchname=@switchName and changeDate = (select MAX(changedate) from HistoryForwardDatabase where portName = @port and switchname=@switchName)
IF(@changedmacAdress is null and @changedvlan is null)
begin
insert into HistoryForwardDatabase (macAdress,portname,changeDate,switchName,vlan) select macAdress,portName,@dateNow,switchName,vlan from @table1 where portName = @port and switchName =@switchName
end
END
This query might do the trick for you: