我正在使用由此處成員之一提供的解決方案來遍歷所有記錄(當前大約爲1000)並對每條記錄執行大約60個SELECT查詢。這大約有6萬個計算結果。這是每天一次。我擔心的是,在這種情況下,所有記錄的「循環」是否是最有效和最快的。通過SQL表循環並執行多個查詢的最快方法
DECLARE @LastCustomerID CHAR(10)
SET @LastCustomerID = 0
-- define the customer ID to be handled now
DECLARE @CustomerIDToHandle CHAR(10)
-- select the next customer to handle
SELECT TOP 1 @CustomerIDToHandle = bl_id
FROM dbo.bl
WHERE bl_id > @LastCustomerID AND status = 'a'
ORDER BY bl_id
-- as long as we have customers......
WHILE @CustomerIDToHandle IS NOT NULL
BEGIN
-- call your sproc. this is where i have the 60 SQL SELECT queries defined
-- in another stored procedure called myStoredProc. it just takes the parameter
-- @CustomerIDToHandle provided here and uses it in the where clauses
EXEC myStoredProc @CustomerIDToHandle
-- set the last customer handled to the one we just handled
SET @LastCustomerID = @CustomerIDToHandle
SET @CustomerIDToHandle = NULL
-- select the next customer to handle
SELECT TOP 1 @CustomerIDToHandle = bl_id
FROM dbo.bl
WHERE bl_id > @LastCustomerID AND status = 'a'
ORDER BY bl_id
END
問題是這是否是執行上述場景的最有效方式。我正在尋找替代品,如果有任何... – dido 2012-04-03 15:44:50
「最有效和最快」的方法是重寫'myStoredProc',並在那裏做一切與你在'dbo.bl'的連接。 – 2012-04-03 15:45:44
幾乎肯定不是。正如你正確地計算出你正在執行60,000個選擇查詢。你對這些查詢的輸出做了什麼,是否有必要一次完成這一個客戶? SQL是基於集合的,並且在可能的情況下應該避免循環,幾乎總是有一個更高效的基於集合的解決方案。 – GarethD 2012-04-03 15:46:16