我向触发器FOR UPDATE添加了两个update语句,但是该列不会更新,不确定我做错了什么。请参见下面两个语句的示例。
表Relationship
Update Profile
Set LDR = 1
From inserted, Profile
Where inserted.TARGET_ID = profile.ID
And inserted.RELATION_TYPE = 'LEADER'
Update Profile
Set LDR = 0
From Deleted, Profile
Where Deleted.Target_ID = profile.ID
And Deleted.RELATION_TYPE = 'LEADER'
个人资料表:
ID | LDR |
--------+-----+
4658632 | 0 |
关系表:
TARGET_ID | Relation_TYPE
----------+--------------
4658632 | LEADER
如果在关系表中插入一条记录,其中Relation_TYPE等于LEADER,则将配置文件表列LDR更新为1。反之亦然。
有什么遗漏吗?
谢谢
答案 0 :(得分:0)
最好这样写:(编辑)
update
p
set
LDR = case profile.ID when inserted.TARGET_ID then 1 else 0 end
from
Profile p
left join inserted i on
i.TARGET_ID = p.ID
left join deleted d on
d.TARGET_ID = p.ID
where
(
i.RELATION_TYPE = 'LEADER' or
d.RELATION_TYPE = 'LEADER'
);
或更安全的方法来确保更新的内容没有歧义:
with cte
as (
select
ID,
[LDR] = 1
from
Profile p
inner join inserted i on
i.TARGET_ID = p.ID
where
i.RELATION_TYPE = 'LEADER'
union all
select
ID,
[LDR] = 0
from
Profile p
inner join deleted d on
d.TARGET_ID = p.ID
where
d.RELATION_TYPE = 'LEADER'
)
update
p
set
LDR = cte.LDR
from
Profile p
inner join cte on
p.ID = cte.ID;
答案 1 :(得分:0)
缺少条件测试。如果它们在同一UPDATE触发器中,则在实际更新记录时,已插入和已删除中都会有值。要解决此问题,请尝试:
WITH Updates AS (
SELECT IsNull(i.Target_ID, d.Target_ID) as Target_ID,
CASE
WHEN i.Target_ID IS NULL
THEN 0
ELSE 1
END as value
FROM (
SELECT Target_ID
FROM inserted
WHERE RELATION_TYPE = 'LEADER'
) as i
FULL OUTER JOIN (
SELECT Target_ID
FROM deleted
WHERE RELATION_TYPE = 'LEADER'
) as d
ON i.Target_ID = d.Target_ID
) u
Update Profile
Set LDR = value
FROM Profile p
INNER JOIN Updates u
ON p.Target_ID = u.Target_ID