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

后端 未结 22 1296
太阳男子
太阳男子 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:33

    I believe an UPDATE FROM with a JOIN will help:

    MS SQL

    UPDATE
        Sales_Import
    SET
        Sales_Import.AccountNumber = RAN.AccountNumber
    FROM
        Sales_Import SI
    INNER JOIN
        RetrieveAccountNumber RAN
    ON 
        SI.LeadID = RAN.LeadID;
    

    MySQL and MariaDB

    UPDATE
        Sales_Import SI,
        RetrieveAccountNumber RAN
    SET
        SI.AccountNumber = RAN.AccountNumber
    WHERE
        SI.LeadID = RAN.LeadID;
    
    0 讨论(0)
  • 2020-11-21 23:33

    The below SQL someone suggested, does NOT work in SQL Server. This syntax reminds me of my old school class:

    UPDATE table2 
    SET table2.col1 = table1.col1, 
    table2.col2 = table1.col2,
    ...
    FROM table1, table2 
    WHERE table1.memberid = table2.memberid
    

    All other queries using NOT IN or NOT EXISTS are not recommended. NULLs show up because OP compares entire dataset with smaller subset, then of course there will be matching problem. This must be fixed by writing proper SQL with correct JOIN instead of dodging problem by using NOT IN. You might run into other problems by using NOT IN or NOT EXISTS in this case.

    My vote for the top one, which is conventional way of updating a table based on another table by joining in SQL Server. Like I said, you cannot use two tables in same UPDATE statement in SQL Server unless you join them first.

    0 讨论(0)
  • 2020-11-21 23:34

    The simple Way to copy the content from one table to other is as follow:

    UPDATE table2 
    SET table2.col1 = table1.col1, 
    table2.col2 = table1.col2,
    ...
    FROM table1, table2 
    WHERE table1.memberid = table2.memberid
    

    You can also add the condition to get the particular data copied.

    0 讨论(0)
  • 2020-11-21 23:34

    Thanks for the responses. I found a solution tho.

    UPDATE Sales_Import 
    SET    AccountNumber = (SELECT RetrieveAccountNumber.AccountNumber 
                              FROM   RetrieveAccountNumber 
                              WHERE  Sales_Import.leadid =RetrieveAccountNumber.LeadID) 
    WHERE Sales_Import.leadid = (SELECT  RetrieveAccountNumber.LeadID 
                                 FROM   RetrieveAccountNumber 
                                 WHERE  Sales_Import.leadid = RetrieveAccountNumber.LeadID)  
    
    0 讨论(0)
提交回复
热议问题