2014-12-04 62 views
0

我創建的存儲過程有效,但是有沒有更高效的方法來做到這一點?公平地說,沒有任何性能受到影響,也不需要優化,但我想知道爲了正確地做事情。優化存儲過程更新並選擇

執行計劃狀態query 1: 17%query 2: 67%query 3: 16%

DECLARE @CurrentVoucherID int; 

SET @CurrentVoucherID = 
    (
     SELECT TOP(1) IdGiftVoucherPhysicalCode 
     from GiftVoucherPhysicalCodes 
     WHERE Activated = 0 and assigned = 0 and Value = 10 
     ORDER BY IdGiftVoucherPhysicalCode 
    ); 

UPDATE GiftVoucherPhysicalCodes 
SET Activated = 1, Activated_at = GETDATE() 
WHERE IdGiftVoucherPhysicalCode = @CurrentVoucherID; 

SELECT * FROM GiftVoucherPhysicalCodes 
WHERE IdGiftVoucherPhysicalCode = @CurrentVoucherID; 
+2

我看不出有什麼不對的,會做同樣的方式... – Hatsjoem 2014-12-04 19:26:49

+0

謝謝你,給我的印象是,選擇被運行兩次儘管有哪些錯誤會導致我返回相同的記錄。 – GJKH 2014-12-04 19:29:09

+1

但執行計劃沒有考慮內存中的索引。如果IdGiftVoucherPhysicalCode被索引,最後在哪裏尋找一個簡單的索引。 – Paparazzi 2014-12-04 20:11:03

回答

0

我可能無法正確理解它,但它看起來像你只是在一個時間運行更新一個記錄?爲什麼不做批量?

UPDATE GiftVoucherPhysicalCodes 
SET Activated = 1, Activated_at = GETDATE() 
WHERE Activated = 0 and assigned = 0 and Value = 10 
+0

我一次更新一個特定記錄,我需要獲取尚未激活的下一個連續可用記錄。 – GJKH 2014-12-04 19:59:41

+1

因此,您無法更新所有尚未激活的記錄,您必須按順序執行此操作嗎? – iddqd 2014-12-04 20:12:26

0

你可以不用可變

UPDATE GiftVoucherPhysicalCodes 
SET Activated = 1, Activated_at = GETDATE() 
WHERE IdGiftVoucherPhysicalCode = (SELECT TOP(1) IdGiftVoucherPhysicalCode 
          from GiftVoucherPhysicalCodes 
          WHERE Activated = 0 and assigned = 0 and Value = 10 
          ORDER BY IdGiftVoucherPhysicalCode) 

SELECT * FROM GiftVoucherPhysicalCodes 
WHERE IdGiftVoucherPhysicalCode = (SELECT TOP(1) IdGiftVoucherPhysicalCode 
          from GiftVoucherPhysicalCodes 
          WHERE Activated = 1 and assigned = 0 and Value = 10 
          ORDER BY IdGiftVoucherPhysicalCode) 
+0

在你的建議中,第二個select語句不會返回所需的記錄,因爲你已經更新記錄以將'activated'設置爲'true'。您無法將其更改爲激活,因爲它仍然會抓取不正確的記錄,除非這是查詢第一次運行。 – GJKH 2014-12-05 15:23:45