我收到此错误消息:
DELETE语句与REFERENCE约束冲突 “ FK_FieldMapper_Field”。数据库“ SCAM”中发生了冲突, 表“ dbo.FieldMapper”的“ FieldID”列。
我有一些具有给定字段数量的accesshelpers。这些字段可由多个访问助手使用。.
删除accesshelper
时,需要检查给定fields
中的accesshelper
是否被其他accesshelpers
使用。如果是的话,我将删除accesshelper,但不要删除这些字段,因为那样会破坏其他accesshelper。
我该怎么办?
到目前为止,这是我自己提出的。
USE [SCAM]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[deleteAccessHelperById]
@Id int
AS
BEGIN
SET NOCOUNT ON;
DECLARE @projectIds TABLE (id int);
INSERT INTO @projectIds ([id]) SELECT dbo.AccessHelperMapper.ProjectID FROM dbo.AccessHelperMapper WHERE dbo.AccessHelperMapper.AccessHelperID = @Id;
DELETE dbo.AccessHelperMapper WHERE dbo.AccessHelperMapper.AccessHelperID = @Id;
DECLARE @fieldIds TABLE (id int);
INSERT INTO @fieldIds ([id]) SELECT dbo.FieldMapper.FieldID FROM dbo.FieldMapper WHERE dbo.FieldMapper.AccessHelperID = @Id;
DECLARE @AHfields TABLE (id int)
Insert into @AHfields
Select fids.id from dbo.FieldMapper, @fieldIds as fids
where dbo.FieldMapper.AccessHelperID != @Id
and fids.id != dbo.FieldMapper.FieldID;
delete dbo.FieldMapper where dbo.FieldMapper.AccessHelperID = @Id and dbo.FieldMapper.FieldID IN (SELECT d.id FROM @AHfields as d);
delete dbo.Field where dbo.Field.ID in (SELECT g.id FROM @AHfields as g);
delete dbo.AccessHelper where dbo.AccessHelper.ID = @Id;
END
答案 0 :(得分:1)
尝试以下代码。希望这就是您想要的:
USE [SCAM]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[deleteAccessHelperById]
@Id int
AS
BEGIN
SET NOCOUNT ON;
DELETE dbo.AccessHelperMapper WHERE dbo.AccessHelperMapper.AccessHelperID = @Id;
DECLARE @fieldIds TABLE (id int);
INSERT INTO @fieldIds ([id]) SELECT dbo.FieldMapper.FieldID FROM dbo.FieldMapper WHERE dbo.FieldMapper.AccessHelperID = @Id
AND dbo.FieldMapper.FieldID NOT IN (SELECT DISTINCT dbo.FieldMapper.FieldID FROM dbo.FieldMapper WHERE dbo.FieldMapper.AccessHelperID != @Id);
delete dbo.FieldMapper where dbo.FieldMapper.AccessHelperID = @Id --and dbo.FieldMapper.FieldID IN (SELECT d.id FROM @fieldIds as d);
delete dbo.Field where dbo.Field.ID in (SELECT g.id FROM @fieldIds as g);
delete dbo.AccessHelper where dbo.AccessHelper.ID = @Id;
END
答案 1 :(得分:0)
首先,您需要进行事务处理,因为部分数据更改无法单独应用。
ALTER PROCEDURE [dbo].[deleteAccessHelperById]
@Id int
AS
BEGIN
SET NOCOUNT ON;
DECLARE @fieldIds TABLE (id int);
BEGIN TRY
BEGIN TRAN
DELETE ahm
FROM dbo.AccessHelperMapper ahm
WHERE ahm.AccessHelperID = @Id;
DELETE fm
OUTPUT DELETED.fieldID
INTO @fieldIds(id)
FROM dbo.FieldMapper fm
WHERE fm.AccessHelperID = @Id
DELETE f
FROM dbo.Field f
WHERE exists(select 1 from @fieldIDs fid where fid.ID = f.ID)
and not exists(
select 1 from dbo.FieldMapper fm
where fm.fieldID = f.ID
and fm.AccessHelperID != @ID -- redundant, may be removed.
)
DELETE ah
FROM dbo.AccessHelper ah
where ah.ID = @Id
COMMIT TRAN
END TRY
BEGIN CATCH
IF XACT_STATE() IN (1, -1)
ROLLBACK TRAN
THROW;
END CATCH
END