嗨我想知道是否有人对如何优化查询有任何提示?
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
答案 0 :(得分:2)
此查询可能会为您解决问题:
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
答案 1 :(得分:-1)
优化是非常抽象的术语。如果您需要优化速度,请尝试使用执行计划。