[英]Running a stored procedure for a Table
我正在嘗試為一個表而不是一行運行一個存儲過程。 我選擇一個存儲過程,因為我需要將記錄插入表中並進行一些更新。 此方法似乎正在掛起。 我看了看解釋計划,但我認為我的邏輯出了點問題,它處理一條記錄並停止。
這是我到目前為止的代碼。 我的存儲過程像野獸一樣運行,我不認為這是問題所在。
---- 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
走
通過提供的信息,我可以看到您的While循環語法錯誤...第一,您沒有在BEGIN END塊的while循環中進行封閉操作,第二,您有一個無限的while循環,它將繼續執行,因為您沒有減少每當您的while循環執行時,都會在您的臨時表中記錄。 嘗試這樣的事情...
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.