我们需要将数据从一个公司复制到另一个公司,为此,我们需要将一个表中存在的所有数据复制到同一表中,但使用不同的公司ID
表1:员工
FName Id Department CatId CompanyId
Pratik 1 1 4 1
Praveen 2 2 3 1
Nilesh 3 2 3 1
表2:组合值
Id Fieldname FieldValue CompanyId
1 Department IT 1
2 Department HR 1
3 Category Staff 1
4 Category Manager 1
我要使用更新的companyid复制同一表中表1和表2中的所有数据
对于下面的表2,查询=>它按预期工作
INSERT INTO ComboValues (Fieldname,FieldValue, CompanyId)
(SELECT Fieldname,FieldValue,2 WHERE Companyid = 1)
结果
表2:组合值
Id Fieldname FieldValue CompanyId
1 Department IT 1
2 Department HR 1
3 Category Staff 1
4 Category Manager 1
5 Department IT 2
6 Department HR 2
7 Category Staff 2
8 Category Manager 2
问题:
但是对于表1,由于表2中存在的部门和类别的更新ID值,我无法执行相同操作
预期结果 表1:员工
FName Id Department CatId CompanyId
Pratik 1 1 4 1
Praveen 2 2 3 1
Nilesh 3 2 3 1
Pratik 4 5 8 2
Praveen 5 6 7 2
Nilesh 6 6 7 2
我可以使用希望避免的循环在C#中执行相同的操作,并且仅对SQL查询执行相同的操作
答案 0 :(得分:2)
您可以使用此:
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;
中进行了测试