SQL Server 2008中的ON DELETE触发器会影响比预期更多的行

时间:2012-12-04 16:34:48

标签: sql sql-server-2008 triggers

我有以下简化的数据库模型:

enter image description here

有工作计划。作业包含位置的对象,但它们没有与表Location明确关联。

我有一个ON DELETE表格Location。我希望触发器将作业的objectid重置为-1。

update dbo.Job 
set objectid = -1, lat = -1, lng = -1, location = null 
from
   (dbo.[Plan] as p 
    inner join dbo.Job as j on (p.planid = j.planid 
                                and p.userid in (select user_id from deleted)))
    inner join deleted as d on j.objectid = d.objectid

我的问题:

此触发器会重置所有匹配的objectids,即使作业属于不同的aspnet_Users。如何才能实现只有相应aspnet_User的作业受触发器影响?

1 个答案:

答案 0 :(得分:1)

我认为您需要同时使用objectiduserid列加入,而不是IN运算符。

另外,我不明白为什么要添加aspnet_Users

update 
        dbo.Job 
set 
        objectid = -1, lat = -1, lng = -1, location = null 
from
        dbo.Job as j 
    join
        dbo.Plan as p   on  p.planid = j.planid
    join
        deleted as d    on  d.objectid = j.objectid
                        and d.user_id = p.userid ;