Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 优化存储过程更新并选择_Sql_Sql Server_Tsql_Query Optimization - Fatal编程技术网

Sql 优化存储过程更新并选择

Sql 优化存储过程更新并选择,sql,sql-server,tsql,query-optimization,Sql,Sql Server,Tsql,Query Optimization,我创建的存储过程可以工作,但是有没有更有效的方法?公平地说,这些都不会对性能造成影响,也不需要进行优化,但为了正确操作,我想知道 执行计划状态为查询1:17%,查询2:67%,查询3:16% DECLARE @CurrentVoucherID int; SET @CurrentVoucherID = ( SELECT TOP(1) IdGiftVoucherPhysicalCode from GiftVoucherPhysicalCodes

我创建的存储过程可以工作,但是有没有更有效的方法?公平地说,这些都不会对性能造成影响,也不需要进行优化,但为了正确操作,我想知道

执行计划状态为查询1:17%,
查询2:67%
查询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;

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

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

你可以不用变量就可以做到

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)

我看不出这有什么问题,我会用同样的方法…谢谢,让我吃惊的是,select运行了两次以返回相同的记录,虽然这有点让我讨厌。但是执行计划没有考虑内存中的索引。如果IdGiftVoucherPhysicalCode被索引,那么最后一个地方是一个微不足道的索引查找。我关心的不是性能,但如果多个进程同时运行,可能会出现错误的结果。如果您在更新之外获得该值,则无法保证在设置参数和运行更新之间不会有其他内容改变该值。您需要显式锁定表或将检查放入update语句本身。使用此技术可能会导致数据完整性混乱。@HLGEM此存储过程仅从请求排队的Web应用程序调用,以避免出现此问题,但公平地说,这可能不是理想的方法。我一次更新一条特定记录,我需要获取下一个未激活的连续可用记录。因此,您无法更新所有未激活的记录,您必须按顺序执行吗?在您的建议中,第二条select语句不会返回所需的记录,因为您已将记录更新为将
激活
设置为
。您也无法将其更改为“已激活”,因为它仍然会捕获不正确的记录,除非这是第一次运行查询。