我在这里有一个查询来更新每个代表最新库存的库存类型的表格。但是,我让它工作的唯一方法是使用游标,这实际上影响了性能。下面是我正在使用的表声明和查询。我能做些什么来更快地达到预期效果吗?
表:
create table #inv (
Rep_LName nvarchar (50),
Rep_FName nvarchar (50),
Rep_ID nvarchar (50),
Rep_Email nvarchar (100),
Rep_Status nvarchar (50),
Rep_BU nvarchar (50),
Sales_Force nvarchar (50),
Territory nvarchar (50),
Sample_Eligibility nvarchar (50),
DM_Name nvarchar (100),
Phys_Inv_Date datetime,
Last_Reconciled datetime,
Inv_Type nvarchar(50),
Days_Since_Last_inv int)
查询:
declare Inventory_type cursor
for select rep_ID, inventory_type
from inv_header
where rep_id in (select rep_id from #inv)
order by call_date desc
declare @rep_ID nvarchar(50)
declare @inventory_type nvarchar(50)
declare @ls_Sql as nvarchar(max)
declare @param as nvarchar(max)
select @ls_Sql=''
select @param=''
-- open cursor
open Inventory_type
fetch next from Inventory_type
into @rep_ID, @inventory_type
while (@@fetch_status = 0)
begin
--use parameterized dynamic sql
SET @param='@rep_ID nvarchar(50),@inventory_type nvarchar(50)'
SET @ls_Sql='update #inv set Inv_Type = @inventory_type
WHERE rep_id = @rep_id AND Inv_Type IS NULL'
--pass parameter to dynamic query
exec sp_executesql @ls_Sql,@param,@rep_ID,@Inventory_type
fetch next from Inventory_type
into @rep_ID, @Inventory_type
end
close Inventory_type
deallocate Inventory_type
答案 0 :(得分:4)
不要使用游标;它们会破坏查询性能。是的,他们在产品中是有原因的,但他们是最后的工具,几乎总是你可以通过基于集合的方法完成工作。一个简单的更新语句在这里可以正常工作。
update i
set i.Inv_Type = h.inventory_type
from #inv i
inner join inv_header h on i.rep_id = h.rep_id
and h.Call_date =
(select Max(Call_Date)
from inv_header i2
where i2.rep_id = i.rep_id)
where i.inv_type is null
答案 1 :(得分:1)
试试这个:
update i set
Inv_Type = h.inventory_type
From #inv i join inv_header h
on h.rep_id = i.Rep_ID
And h.Call_date =
(Select Max(Call_Date)
From inv_header
Where rep_id = i.rep_id)
where i.Inv_Type Is Null
答案 2 :(得分:0)
脱离我的头脑,不知道你的数据库,这样的事情应该有效:
UPDATE #inv set Inv_Type = (SELECT inventory_type FROM inv_header
WHERE #inv.Rep_ID = inv_header.rep_id)
WHERE Inv_Type IS NULL
您也可以将其作为连接进行,根据您拥有的行数可能会更高效。
至少应该让你开始......
答案 3 :(得分:0)
我认为他想要拥有最新通话日期的inv_type ..
update inv
set inv.Inv_Type = ih.inventory_type
from (
select rep_ID, max(call_date) max_call_date
from inv_header
where rep_id in (select rep_id from #inv)
group by rep_ID ) a
inner join inv_header ih
on ih.rep_ID = a.rep_ID
and ih.call_date = a.max_call_date
inner join #inv inv
on inv.rep_ID = ih.rep_id
and inv.Inv_Type is null