我正在尝试从我的主表中删除记录,同时运行我理解的脚本,我主表中的Id在其他8个表中被引用为外键。我不想使用CASCADE DELETE,因为我必须改变表约束。我的主表名为Job,其主键为“Id”,在其他表中引用为外键“JobId”。
在从主Job表中删除之前,如何删除相关表中的外键引用记录。
这是我的下面的代码。评论的代码只是一个预测。
SELECT * FROM [JOB] j WHERE Name=@Name AND Title=@Title AND Zip=@Zip
AND Id<>@Id AND NOT EXISTS (SELECT * FROM NewJob nj WHERE J.Id=nj.Id)
--DELETE FROM [Table1] a WHERE a.JobId = j.Id AND
--DELETE FROM [Table2] F WHERE f.JobId = j.Id AND
--DELETE FROM [Table3] jct WHERE jct.JobId = j.Id AND
--DELETE FROM [Table4] jch WHERE jch.JobId = j.Id AND
--DELETE FROM [Table5] jedu WHERE jedu.JobId = j.Id AND
--DELETE FROM [Table6] jexp WHERE jexp.JobId = j.Id AND
--DELETE FROM [Table7] jflc WHERE jflc.JobId = j.Id AND
--DELETE FROM [Table8] usj WHERE usj.JobId = j.Id AND
DELETE FROM [JOB] WHERE Id IN (SELECT Id FROM [JOB] WHERE Name=@Name AND Title=@Title AND Zip=@Zip AND Id<>@Id)
答案 0 :(得分:1)
首先,您应该注意所有关系,然后您可以根据主查询中的键(ID)对引用的表运行DELETE语句。一个基本想法可能是:
-- how many tables and references? Just to be sure.
EXEC sp_fkeys 'Job'
-- required query for deleting relationships
DELETE FROM ForeignTable WHERE JobId IN (SELECT Id FROM Job WHERE [....])
DELETE FROM ForeignTable2 WHERE JobId IN (SELECT Id FROM Job WHERE [....])
-- main query
DELETE FROM [JOB] WHERE Id IN (SELECT Id FROM [JOB] WHERE Name=@Name AND Title=@Title AND Zip=@Zip AND Id<>@Id)
希望它有所帮助。
答案 1 :(得分:1)
如果你创建一个临时表来存储你想要从主表中发现它们的id,那么这样的东西可能是最容易的。在事务中也要这样做,以维护ACID属性。
Begin Transaction
Create Table #JobIDsToDelete (JobID int);
Insert Into #JobIDsToDelete
Select ID
From [Job] As j
Left Join NewJob As nj On j.ID = nj.ID
Where Name = @Name
And Title = @Title
And Zip = @Zip
And ID <> @ID
And nj.ID Is Null;
Delete From Table1 Where JobID In (Select JobID From #JobIDsToDelete);
Delete From Table2 Where JobID In (Select JobID From #JobIDsToDelete);
...
Delete From [Job] Where ID In (Select JobID From #JobIDsToDelete);
Commit Transaction