我有两张表如下:
active_employee
,包含列id,email_id,作业,位置和project_id
project_relation
,其中包含列id,email_id和project_id。
我的问题是我想更新project_relation表的project_id列,条件是如果两个表中project_id的值不相同,那么它必须从“active_employee”表中获取值并更新project_relation相应email_id的表。
帮我解决这个问题!
答案 0 :(得分:0)
我相信通过JOIN进行UPDATE FROM会有所帮助:
UPDATE
project_relation
SET
project_relation.project_id = active_employee.project_id
FROM
project_relation PR
INNER JOIN
active_employee AE
ON
PR.columns_id = AE.columns_id
只需检查下划线..它可能会产生问题..您可以删除它并在db列名称中进行更改。
或者只是尝试这个 -
UPDATE project_relation SET project_relation.project_id = active_employee.project_id where project_relation.columns_id = active_employee.columns_id;
答案 1 :(得分:0)
我想我得到了你需要的东西。我创建了一些临时表来替换您的实际表进行测试。
由于更新表,我使用子查询重命名了一些列名以删除不明确的名称:
DECLARE @ACTIVE_EMPLOYEE TABLE (columnid UNIQUEIDENTIFIER, emailid UNIQUEIDENTIFIER, job VARCHAR(200), location VARCHAR(200), projectid UNIQUEIDENTIFIER)
DECLARE @PROJECT_RELATION TABLE (columnid UNIQUEIDENTIFIER, emailid UNIQUEIDENTIFIER, projectid UNIQUEIDENTIFIER)
UPDATE @PROJECT_RELATION
SET projectid = active.proid
FROM (SELECT columnid,
emailid [emid],
job,
location,
projectid [proid]
FROM @ACTIVE_EMPLOYEE) active
WHERE active.emid = emailid
AND active.proid <> projectid