从性能角度来看,使用 SQL Server 2016 或 2017 匹配(替换)temp table 中每一行中的每个值的正确方法是什么?

What is the correct way from performance perspective to match(replace) every value in every row in temp table using SQL Server 2016 or 2017?

我想知道我应该在 SQL Server 2016 或 2017(CTE、LOOP、JOINS、CURSOR、REPLACE 等)中使用什么来匹配(替换)每个值 每行 在温度 table 中? 性能方面 的最佳解决方案是什么?

来源Table

|id |id2|  
| 1 | 2 |  
| 2 | 1 |  
| 1 | 1 |  
| 2 | 2 | 

映射Table

|id  |newid|  
| 1  | 3   |   
| 2  | 4   |  

预期结果

|id |id2|  
| 3 | 4 |  
| 4 | 3 |  
| 3 | 3 |   
| 4 | 4 | 

您可以加​​入第二个 table 到第一个 table 两次:

WITH cte AS (
    SELECT
        t1.id AS id_old,
        t1.id2 AS id2_old,
        t2a.newid AS id_new,
        t2b.newid AS id2_new
    FROM table1 t1
    LEFT JOIN table2 t2a
        ON t1.id = t2a.id
    LEFT JOIN table2 t2b
        ON t1.id2 = t2b.id
)

UPDATE cte
SET
    id_old = id_new,
    id2_old = id2_new;

Demo

不确定您是否只需要 select,或者更新,或者插入另一个 table。无论如何,我上面给出的核心逻辑应该适用于所有这些情况。

只做self join

SELECT t1.id2 as id, t2.id2 
FROM table1 t
INNER JOIN table2 t1 on t1.id = t.id
INNER JOIN table2 t2 on t2.id = t.id2

您需要在更新查询时应用联接。像这样:

Update tblA set column1 = 'something', column2 = 'something'
from actualName tblA
inner join MappingTable tblB 
on tblA.ID = tblB.ID

此查询会将每一行与 id 进行比较,如果匹配,那么它将 update/replace 列的值,如您所愿。 :)

如果您正确设置了索引,这可能是此处发布的解决方案的最佳性能:

select (select [newid] from MappingTable where id = [ST].[id]) [id],
       (select [newid] from MappingTable where id = [ST].[id2]) [id2]
from SourecTable [ST]