优化存储过程更新和选择

时间:2014-12-04 19:24:45

标签: sql sql-server tsql query-optimization

我创建的存储过程有效,但是有更有效的方法吗?公平地说,没有任何性能损失,也不需要优化,但我想知道为了正确地做事。

执行计划声明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 个答案:

答案 0 :(得分:0)

我可能无法正确理解它,但看起来您只是一次运行更新一条记录?为什么不批量做?

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

答案 1 :(得分: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)