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

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

    In case the tables are in a different databases. (MSSQL)

    update database1..Ciudad
    set CiudadDistrito=c2.CiudadDistrito
    
    FROM database1..Ciudad c1
     inner join 
      database2..Ciudad c2 on c2.CiudadID=c1.CiudadID
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-21 23:11

    Here's what worked for me in SQL Server:

    UPDATE [AspNetUsers] SET
    
    [AspNetUsers].[OrganizationId] = [UserProfile].[OrganizationId],
    [AspNetUsers].[Name] = [UserProfile].[Name]
    
    FROM [AspNetUsers], [UserProfile]
    WHERE [AspNetUsers].[Id] = [UserProfile].[Id];
    
    0 讨论(0)
  • 2020-11-21 23:12

    Oracle 11g

    merge into Sales_Import
    using RetrieveAccountNumber
    on (Sales_Import.LeadId = RetrieveAccountNumber.LeadId)
    when matched then update set Sales_Import.AccountNumber = RetrieveAccountNumber.AccountNumber;
    
    0 讨论(0)
  • 2020-11-21 23:13

    it works with postgresql

    UPDATE application
    SET omts_received_date = (
        SELECT
            date_created
        FROM
            application_history
        WHERE
            application.id = application_history.application_id
        AND application_history.application_status_id = 8
    );
    
    0 讨论(0)
  • 2020-11-21 23:15

    try this :

    UPDATE
        Table_A
    SET
        Table_A.AccountNumber = Table_B.AccountNumber ,
    FROM
        dbo.Sales_Import AS Table_A
        INNER JOIN dbo.RetrieveAccountNumber AS Table_B
            ON Table_A.LeadID = Table_B.LeadID 
    WHERE
        Table_A.LeadID = Table_B.LeadID
    
    0 讨论(0)
提交回复
热议问题