2013-11-25 50 views
0

我正在嘗試爲表而不是一行運行存儲過程。我選擇一個存儲過程,因爲我需要將記錄插入到表中並進行一些更新。 這種方法似乎掛起。我看了解解釋計劃,但我認爲我的邏輯有些問題,它會處理一條記錄並停止。爲表運行存儲過程

這是我到目前爲止的代碼。我的存儲過程像野獸一樣運行,我不認爲這是問題。

---- Create a driver table for the stored procedure to run off . 
drop table #Driver_Table 

select col1, col2 
IDENTITY(int) AS idcol 
INTO #Driver_Table 
FROM CUSTOMER 
--- Contains about 37 k records 

--- Index added for performance 
CREATE CLUSTERED INDEX IDX_C_Driver_Table_UserID ON #Driver_Table(idcol) 

-- Define the last customer ID to be handled 
DECLARE @LastCustomerID INT 
SET @LastCustomerID = 0 

--- Other parameter the queries will use 
DECLARE @idcol INT 
DECLARE @col1 datetime 
DECLARE @col2 varchar(200) 

SET @idcol= 0 

-- Iterate over all customers 
BEGIN 

-- Get next customerId 
SELECT TOP 1 @idcol = idcol FROM #Driver_Table 
WHERE idcol > @LastCustomerID 

select TOP 1 @col1=col1 
FROM #Driver_Table 
WHERE idcol > @LastCustomerID 

select TOP 1 @col2=col2 
FROM #Driver_Table 
WHERE idcol > @LastCustomerID 

---- To get the process to end when last customer is processed. 
WHILE @col2 NOT NULL 

-- call your sproc 
EXEC SP @col1,@Col2 

-- set the last customer handled to the one we just handled 
SET @LastCustomerID = @idcol 
SET @col2 = NULL 

-- select the next customer to handle 
SELECT TOP 1 @col2 = col2 
FROM #Driver_Table 
WHERE idcol > @LastCustomerID 

END 

SQL SERVER 2005

GO

+0

你不能「運行一個表的存儲過程」 - 但你可以改變存儲過程(或添加一個新的),將處理一個相對於所有這個臨時表/光標忙於工作。如果你顯示SP的定義,那麼有人可以幫你做到這一點。 –

回答

1

隨着提供的信息,我可以看到有while循環的語法是錯誤的......你還沒有封閉運行在while循環開始結束塊1, 2nd你有一個無限的while循環,它會繼續執行,因爲每次執行while循環時都不會減少temp表中的記錄數。嘗試像這樣...

WHILE (EXISTS (SELECT * FROM #Driver_Table)) 

BEGIN 

    SELECT TOP 1 @idcol = idcol, @col1=col1, @col2=col2 
    FROM #Driver_Table 


    EXEC SP @col1,@Col2 

    DELETE FROM #Driver_Table 
    WHERE idcol = @idcol; 


END 
+0

雖然我的存儲過程顯示出一點性能問題,但它可以工作。我可以就此提出一個單獨的問題。謝謝。 –

+0

很高興幫助。我不知道EXEC SP是什麼,它做了什麼,但代碼可以簡化。總是有更好的方式做他們說的事:) –