2011-11-19 39 views
0

我有一個SQL存儲過程,因爲某些緩存的值而永遠不會結束。但這只是調試過程後的猜測。Microsoft SQL Server在存儲過程中使用過時的值

while @poid is not NULL 
    BEGIN 

     Update Item set Sales = (Select Sales from V_ITEM_Hierarchy where [email protected]) where [email protected] 

     Select @poid = i.ItemID 
     from V_ITEM_Hierarchy t inner join Item i on (t.POID = i.POID) 
     where (abs(coalesce(t.Sales,0)-coalesce(i.Sales,0)) > 0.0001 

    END 

我更新表項的值「銷售」與一個名爲「V_ITEM_Hierarchy」視圖的銷售值,然後再尋找它們是不同的值。當我通過過程進行調試時,即使銷售值因更新而不再不同,select-statement始終會返回相同的值。

我試圖插入命令「DBCC DROPCLEANBUFFERS」,但select語句仍然返回舊值。

回答

2

如果第二個查詢沒有返回任何行,@poid的值將不會被更新。你需要的是

while @poid is not NULL 
BEGIN 

    Update Item set Sales = (Select Sales from V_ITEM_Hierarchy where [email protected]) where [email protected] 

    set @poid = null 

    Select @poid = i.ItemID 
    from V_ITEM_Hierarchy t inner join Item i on (t.POID = i.POID) 
    where (abs(coalesce(t.Sales,0)-coalesce(i.Sales,0)) > 0.0001 

END 
+0

是的,就是這樣。現在它正在工作!非常感謝。 – Preli

0

我認爲你會更好地將它改爲遊標,因爲你現在總會有無限循環的可能性。

DECLARE @poid INT 

DECLARE item_cursor CURSOR FOR 
Select i.ItemID 
    from V_ITEM_Hierarchy t inner join Item i on (t.POID = i.POID) 
    where (abs(coalesce(t.Sales,0)-coalesce(i.Sales,0)) > 0.0001 

OPEN item_cursor 

FETCH NEXT FROM item_cursor INTO @poid 
WHILE @@FETCH_STATUS = 0 
    BEGIN 
    Update Item set Sales = (Select Sales from V_ITEM_Hierarchy where [email protected]) where [email protected] 

    FETCH NEXT FROM item_cursor INTO @poid 
    END 

DEALLOCATE item_cursor 
+0

恐怕V_ITEM_Hierarchy取其值了項目表,這意味着每個項目表是改變了V_ITEM_Hierarchy值可以是不同的時間。 – Preli

+0

啊,這是一個無賴。我看到的一件事是視圖返回非常奇怪的數據,當視圖中的一個表的數據結構發生變化時,視圖不會重新編譯。 –