我有删除Tsql的问题,当它删除关联记录时,有人可以帮我解决问题吗
ALTER PROCEDURE [dbo].[Delete_Resource]
@ResID INT,
@UserID uniqueidentifier
AS
BEGIN
DELETE FROM [ideaPark_DB].[dbo].[Topics_Resources]
WHERE [ideaPark_DB].[dbo].[Topics_Resources].ResourceID = @ResID
DELETE FROM [ideaPark_DB].[dbo].[Likes]
WHERE [ideaPark_DB].[dbo].[Likes].resourceID = @ResID
declare @BookmarkID INT;
SET @BookmarkID = (SELECT [ideaPark_DB].[dbo].[Bookmarks].id FROM [ideaPark_DB].[dbo].[Bookmarks] WHERE [ideaPark_DB].[dbo].[Bookmarks].resourceID = @ResID and Bookmarks.userID = @UserID)
DELETE FROM [ideaPark_DB].[dbo].[Bookmarks]
WHERE [ideaPark_DB].[dbo].[Bookmarks].resourceID = @ResID
DELETE FROM [ideaPark_DB].[dbo].Bookmarks_Groups
WHERE Bookmarks_Groups.bookmarkID = @BookmarkID
delete FROM [ideaPark_DB].[dbo].[Resources_Relationship]
WHERE [ideaPark_DB].[dbo].[Resources_Relationship].fk_parent = @ResID
DELETE FROM [ideaPark_DB].[dbo].[Skills_Resources]
WHERE [ideaPark_DB].[dbo].[Skills_Resources].ResourceID = @ResID
DELETE FROM [ideaPark_DB].[dbo].[Resources]
WHERE [ideaPark_DB].[dbo].[Resources].Id = @ResID
END
错误
发生严重错误。 DELETE语句与REFERENCE约束“FK_Resources_Relationship_Resources1”冲突。冲突发生在数据库“ideaPark_DB”,表“dbo.Resources_Relationship”,列'fk_child'中。该语句已终止。 -
答案 0 :(得分:1)
在最终删除Resources
delete FROM [ideaPark_DB].[dbo].[Resources_Relationship]
WHERE [ideaPark_DB].[dbo].[Resources_Relationship].fk_chid = @ResID
你的Resources_Relationship
表有两个FK回到Resources
表,你只处理其中一个。
答案 1 :(得分:0)
我看到两个问题:
第一个:
DELETE FROM [ideaPark_DB].[dbo].[Bookmarks]
WHERE [ideaPark_DB].[dbo].[Bookmarks].resourceID = @ResID
DELETE FROM [ideaPark_DB].[dbo].Bookmarks_Groups
WHERE Bookmarks_Groups.bookmarkID = @BookmarkID
我会更改这些删除的顺序,因为bookmark_groups是书签和组之间的中间表。
第二个:
删除后:
DELETE FROM [ideaPark_DB].[dbo].[Resources_Relationship]
WHERE [ideaPark_DB].[dbo].[Resources_Relationship].fk_parent = @ResID
您必须添加以下内容:
DELETE FROM [ideaPark_DB].[dbo].[Resources_Relationship]
WHERE [ideaPark_DB].[dbo].[Resources_Relationship].fk_child = @ResID