我正在尝试使用Azure的SQL数据库进行一些批量删除,我按如下方式运行语句:
delete from DbRoles where AccountID = 41;
可以预期AccountID为41的所有行,但它只删除表中最后一个匹配的行。我发现这是真的,无论是使用常规的“where”语句还是使用像
这样的子查询 where Id in (select Id from DbRoles where AccountID = 41)
(并Id in (41, 42, 43, ... etc)
也失败了)有没有人有任何想法可能会这样?
-----编辑-----
在评论中回答一些问题的更多信息: Roles表确实有一个删除触发器(感谢提示@Steve Ford)我们有一个Closure表连接到Roles表,并在角色表中发生操作时通过触发器进行更新。其中一个是删除触发器,如下所示:
CREATE TRIGGER [tr_dbRole_delete]
ON [dbo].[DbRoles]
Instead of DELETE
AS
BEGIN
declare @roleID int;
select @roleID = Id from deleted
--delete self closure
delete from DbRoleClosures
where childID = @roleID and parentID = @roleID
--delete role
delete from DbRoles
where Id = @roleID
END
我认为“相反”声明可能是我的罪魁祸首,任何人都可以验证吗?
答案 0 :(得分:1)
由于此声明,您的触发器只删除了一行:
select @roleID = Id from deleted
删除多行时,@ roleID将设置为其中一个ID,具体取决于SQL Server查询已删除表的顺序。
触发器应为:
CREATE TRIGGER [tr_dbRole_delete]
ON [dbo].[DbRoles]
Instead of DELETE
AS
BEGIN
--delete self closure
delete from DbRoleClosures
where childID = parentId AND
childID in (SELECT Id from deleted)
--delete role
delete from DbRoles
where Id in (SELECT Id from deleted)
END