ALTER TABLE [AKUZ].[T_CDA_DOCUMENT_PROTOCOLEXTRACT] DROP CONSTRAINT [FK_T_REK_EVENT_T_CDA_DOCUMENT_PROTOCOLEXTRACT_RekEvent]
GO
DROP INDEX [UQ_T_CDA_DOCUMENT_PROTOCOLEXTRACT_RekEvent] ON [AKUZ].[T_CDA_DOCUMENT_PROTOCOLEXTRACT]
GO
alter table [AKUZ].[T_CDA_DOCUMENT_PROTOCOLEXTRACT] drop column RekEvent_UQ
update cda
set RekEvent = (select top 1 re.RekExpertiseID from AKUZ.T_REK_EXPERTISE re where re.RekEvent = cda.RekEvent order by re.BeginTime desc)
from AKUZ.T_CDA_DOCUMENT_PROTOCOLEXTRACT cda
GO
EXEC sp_rename 'AKUZ.T_CDA_DOCUMENT_PROTOCOLEXTRACT.RekEvent', 'RekExpertise', 'COLUMN';
GO
ALTER TABLE [AKUZ].[T_CDA_DOCUMENT_PROTOCOLEXTRACT] ADD CONSTRAINT [FK_T_REK_EXPERTISE_T_CDA_DOCUMENT_PROTOCOLEXTRACT_RekExpertise]
FOREIGN KEY([RekExpertise]) REFERENCES [AKUZ].[T_REK_EXPERTISE] ([RekExpertiseID])
GO
ALTER TABLE [AKUZ].[T_CDA_DOCUMENT_PROTOCOLEXTRACT]ADD [RekExpertise_UQ] AS (CASE WHEN [RekExpertise] IS NOT NULL THEN NULL ELSE [CdaDocumentID] END)
GO
SET ARITHABORT ON
SET CONCAT_NULL_YIELDS_NULL ON
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
SET NUMERIC_ROUNDABORT OFF
GO

/****** Object:  Index [UQ_T_CDA_DOCUMENT_PROTOCOLEXTRACT_RekEvent]    Script Date: 04.05.2023 14:57:50 ******/
CREATE UNIQUE NONCLUSTERED INDEX [UQ_T_CDA_DOCUMENT_PROTOCOLEXTRACT_RekExpertise] ON [AKUZ].[T_CDA_DOCUMENT_PROTOCOLEXTRACT]
(
  [RekExpertise] ASC,
  [RekExpertise_UQ] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO