SQL获取在n秒内创建的重复项,更新其他表中的f键行,删除重复项

时间:2018-03-24 03:43:54

标签: sql sql-server

我有一个表InspectionNotes - 我能够获得在n秒内创建的重复注释 - 这很有效。

问题是当我尝试删除rn> 1我遇到了一个外键约束 - 在 InspectionHoldDurations列PutOnHoldNoteID。

表检查说明:

CREATE TABLE [dbo].[InspectionNotes](
[InspectionNoteID] [uniqueidentifier] NOT NULL,
[InspectionID] [uniqueidentifier] NOT NULL,
[UserRoleID] [uniqueidentifier] NOT NULL,
[Notes] [nvarchar](max) NOT NULL,
[CurrentInspectionStatusID] [int] NOT NULL,
[CreatedOn] [datetime] NOT NULL,
[InspectionNoteTypeID] [int] NOT NULL,
[QuickAnswerID] [uniqueidentifier] NULL,
[Reviewed] [bit] NOT NULL CONSTRAINT [DF_InspectionNotes_Reviewed]  DEFAULT ((0)),
[DateReviewed] [datetime] NULL,
[ReviewedByUserRoleID] [uniqueidentifier] NULL,
 CONSTRAINT [PK_InspectionNotes] PRIMARY KEY CLUSTERED

表InspectionHoldDurations

CREATE TABLE [dbo].[InspectionHoldDurations](
[InspectionHoldDurationID] [uniqueidentifier] NOT NULL,
[InspectionID] [uniqueidentifier] NOT NULL,
[PutOnHoldByRoleID] [uniqueidentifier] NOT NULL,
[TookOffHoldByRoleID] [uniqueidentifier] NULL,
[StartDate] [datetime] NOT NULL,
[EndDate] [datetime] NULL,
[TotalHoldDurationMinutes] [int] NULL,
[ExpirationDate] [datetime] NULL,
[PutOnHoldNoteID] [uniqueidentifier] NULL,
[TakeOffHoldNoteID] [uniqueidentifier] NULL,
PRIMARY KEY CLUSTERED 
(
[InspectionHoldDurationID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

我目前要删除重复项的查询:

;WITH CTE1
AS (
SELECT  
[InspectionNoteID],
ROW_NUMBER() OVER (partition by InspectionID, Notes,UserRoleID,CurrentInspectionStatusId,InspectionNoteTypeID,QuickAnswerID,Reviewed,DateReviewed,ReviewedByUserRoleID,DATEDIFF(ss,'1/1/1970',CreatedOn) / 10000 ORDER BY createdon ASC) AS rn
FROM [DBO].[InspectionNotes] 
)
DELETE inote
FROM
[DBO].[InspectionNotes] inote
INNER JOIN 
CTE1
ON inote.InspectionNoteID = CTE1.[InspectionNoteID]
where CTE1.rn > 1
AND NOT EXISTS (SELECT * FROM [DBO].[InspectionHoldDurations] WHERE PutOnHoldNoteID = CTE1.InspectionNoteID or TakeOffHoldNoteID = CTE1.InspectionNoteID)

我想摆脱AND NOT EXISTS(SELECT * FROM [DBO]。[InspectionHoldDurations],而是用CTE1中相应的行更新此表,其中rn = 1 - 然后从InspectionNotes中删除,其中rn> 1. I我试过这个并且不断收到fkey错误。

0 个答案:

没有答案