Tips on how to optimize and SQL Query
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= @m开发者_如何学PythonacAdress 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:
INSERT INTO HistoryForwardDatabase (macAdress, portname, changeDate, switchName, vlan)
SELECT f.macAdress, f.portName, h.changeDate, f.switchName, f.vlan
FROM ForwardDatabase AS f
LEFT JOIN HistoryForwardDatabase AS h
ON f.macAdress= h.macAdress
AND f.vlan = h.vlan
AND f.portName = h.portName
AND f.switchname= h.switchName
AND h.changeDate = (SELECT MAX(h2.changedate)
FROM HistoryForwardDatabase h2
WHERE h2.portName = h.portName
AND h2.switchname h.switchName)
WHERE h.macAddress IS NULL AND h.vlan IS NULL
Optimization is very abstract term. In case you need optimize speed try use Execution plan.
精彩评论