简体   繁体   中英

Which is better to select IDs of updated data: Join with Temp table or using OUTPUT INTO?

I want to select IDs of updated data and return them to client. which way is better?

1- using OUTPUT INTO :

DECLARE @TempE TABLE (  
    Id BIGINT NOT NULL,    
    Token VARCHAR(36) NOT NULL
);

UPDATE [dbo].[MyTable]
   SET [State] = 3  -- Expired
OUTPUT Deleted.[Id], Deleted.[Token]
  INTO @TempE
 WHERE [ExpireDate] < GETDATEUTC();

SELECT Id,
       Token
FROM @TempE;

2- using a temp table, update with join :

SELECT 
    [E].[Id],
    [E].[Token]
INTO #tempTb
FROM [dbo].[MyTable]
WHERE [ExpireDate] < GETUTCDATE();

UPDATE [M]
SET [M].[State] = 3 -- Expired
FROM [dbo].[MyTable] AS [M]
INNER JOIN #tempTb AS [T] ON [T].[Id] = [M].[Id];

SELECT Id,
       Token
FROM #tempTb;

The server is SQL Server 2016, and no more than 500 rows are expected to be updated in each execution.

thanks for any help :)

As I mention in the comment, there's no need for a table variable/temporary table here, just OUTPUT the result set:

UPDATE [dbo].[MyTable]
   SET [State] = 3  -- Expired
OUTPUT inserted.[Id], inserted.[Token]
 WHERE [ExpireDate] < GETDATEUTC();

Also, personally, I would use inserted here, not deleted , though they should be semantically the same for this scenario (unless you have a trigger of something effecting the values of Token or Id in an UPDATE ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM