有没有办法在 t1 和 t1 中加快对百万行的查询?

Is there a way to speed up this query for million rows in both t1 and t1?

Table t1 的主键为 NUMBER,我们必须使用 Table t2 的行设置属性 A、B、C...,因此使用 PIVOT。

执行此查询需要 4 个多小时。

有什么办法可以改善吗?

DECLARE @number [varchar](40)

    DECLARE cursor CURSOR FOR 
    SELECT DISTINCT(t1.NUMBER) 
    FROM [TABLE1] t1
    INNER JOIN [TABLE2] t2
    ON t1.NUMBER = t2.NUMBER

    OPEN cursor

    BEGIN TRANSACTION
    FETCH NEXT FROM cursor INTO @number

    WHILE(@@FETCH_STATUS = 0)
        BEGIN
        UPDATE t1
        SET A = piv.A,
            B= piv.B,
            C= piv.C, ...
        FROM
            (SELECT A, B, C, ... 
            FROM
                (SELECT VALUE, NAME
                FROM t2
                WHERE NUMBER = @number
                ) d
                PIVOT
                (MAX(VALUE)
                FOR NAME IN (A, B, C, ...
                ) p
            ) AS piv
        WHERE t1.NUMBER = @number

    FETCH NEXT FROM cursor INTO @number
    END
    COMMIT TRANSACTION

按照 SQL 的方式去做。

从数据透视更新。

UPDATE t1
SET A = t2.A
  , B = t2.B
  , C = t2.C
FROM TABLE1 t1
JOIN (
    SELECT *
    FROM (
      SELECT [NUMBER], NAME, [VALUE]
      FROM TABLE2
      WHERE NAME IN ('A','B','C')
    ) Src
    PIVOT (
      MAX([VALUE])
      FOR NAME IN ([A],[B],[C]) 
    ) Pvt
) t2 ON t2.[NUMBER] = t1.[NUMBER]

更新前

select * from TABLE1
NUMBER A B C
1 null null null
2 null null null

更新后

select * from TABLE1
NUMBER A B C
1 a one be one you see
2 a two is too too be or not to see

演示 db<>fiddle here