Replicate Data in same table with modified Relations in SQL

后端 未结 1 663
不思量自难忘°
不思量自难忘° 2021-01-24 03:16

We had a requirement to copy data from one company to another, for this we need to replicate all the data present in one table into the same table but with a different company i

相关标签:
1条回答
  • 2021-01-24 03:43

    You could use this:

    WITH tmp_table AS
    (
        SELECT o.id AS id_old, n.id AS id_new
        FROM combovalues o
        INNER JOIN combovalues n 
        ON o.fieldname = n.fieldname AND o.fieldvalue = n.fieldvalue
        WHERE o.companyid = 1 AND n.companyid = 2
    )
    INSERT INTO employee (fname, department, catid, companyid)
    SELECT fname, d.id_new, c.id_new, 2
    FROM employee e
    LEFT JOIN tmp_table d
    ON e.department = d.id_old
    LEFT JOIN tmp_table c
    ON e.catid = c.id_old
    WHERE companyid = 1;
    

    Tested in rextester

    0 讨论(0)
提交回复
热议问题