2014-12-04 51 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