我在這裏有一個查詢來更新每個代表最近的庫存清單類型的表。但是,我得到它的唯一方法是使用遊標,這真的會影響性能。以下是我正在使用的表格聲明和查詢。我還能做些什麼來更快地達到預期效果?如何提高查詢性能?
表:
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
當然你可以做到這一點作爲UPDATE語句? – Simon 2013-05-10 13:19:26
RBAR警報! (通過激動的行排列)......... – granadaCoder 2013-05-10 13:21:25
這裏是一個學習的例子.....它展示了一個RBAR解決方案,然後將它重構爲一個基於集合的解決方案。 http://granadacoder.wordpress.com/2008/07/24/cursors-setbased-and-scalar-udf/ – granadaCoder 2013-05-10 13:23:00