“ Common.XXX”数据表正在创建到临时表中。但这会带来一些性能问题。如何删除临时表?或您有什么建议?最佳做法是什么?使用CTE优于临时表。我对吗?如何在查询性能以下进行改进?
CREATE PROCEDURE [Common].[GetXYZ]
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRAN;
DROP TABLE IF EXISTS #xxx;
SELECT TOP (1)
*
INTO #xxx
FROM Common.Import WITH (UPDLOCK)
WHERE State = 1
ORDER BY Id;
UPDATE Common.Import
SET State = 2
WHERE Id IN (
SELECT Id FROM #xxx
);
UPDATE #xxx
SET State = 2;
SELECT *
FROM #xxx;
COMMIT;
END;
答案 0 :(得分:3)
更好的方法如下。这样可以避免在当前代码中加载不必要的操作(我假设Id
是唯一的)
WITH CTE AS
(
SELECT TOP (1) *
FROM Common.XXX WITH (UPDLOCK)
WHERE State = 1
ORDER BY Id
)
UPDATE CTE
SET State = 2
OUTPUT INSERTED.*;