SQL update from one Table to another based on a ID match

后端 未结 22 1578
太阳男子
太阳男子 2020-11-21 22:49

I have a database with account numbers and card numbers. I match these to a file to update any card numbers to the account number, so

22条回答
  •  春和景丽
    2020-11-21 23:10

    I'd like to add one extra thing.

    Don't update a value with the same value, it generates extra logging and unnecessary overhead. See example below - it will only perform the update on 2 records despite linking on 3.

    DROP TABLE #TMP1
    DROP TABLE #TMP2
    CREATE TABLE #TMP1(LeadID Int,AccountNumber NVarchar(50))
    CREATE TABLE #TMP2(LeadID Int,AccountNumber NVarchar(50))
    
    INSERT INTO #TMP1 VALUES
    (147,'5807811235')
    ,(150,'5807811326')
    ,(185,'7006100100007267039');
    
    INSERT INTO #TMP2 VALUES
    (147,'7006100100007266957')
    ,(150,'7006100100007267039')
    ,(185,'7006100100007267039');
    
    UPDATE A
    SET A.AccountNumber = B.AccountNumber
    FROM
        #TMP1 A 
            INNER JOIN #TMP2 B
            ON
            A.LeadID = B.LeadID
    WHERE
        A.AccountNumber <> B.AccountNumber  --DON'T OVERWRITE A VALUE WITH THE SAME VALUE
    
    SELECT * FROM #TMP1
    

提交回复
热议问题