ALTER TABLE [AKUZ].[T_EVENT_REHABILITATION_CARD] ADD [RehabCourse] uniqueidentifier NULL
GO

UPDATE EVENT_CARD
	SET EVENT_CARD.RehabCourse = REHAB_COURSE.RehabCourseID
FROM [AKUZ].[T_EVENT_REHABILITATION_CARD] EVENT_CARD
	INNER JOIN [AKUZ].[T_REHAB_COURSE] REHAB_COURSE ON EVENT_CARD.EventBase = REHAB_COURSE.EventBase

ALTER TABLE [AKUZ].[T_EVENT_REHABILITATION_CARD] ADD CONSTRAINT [FK_T_REHAB_COURSE_T_EVENT_REHABILITATION_CARD_RehabCourse]
FOREIGN KEY([RehabCourse]) REFERENCES [AKUZ].[T_REHAB_COURSE] ([RehabCourseID])
GO

ALTER TABLE [AKUZ].[T_REHAB_COURSE] DROP CONSTRAINT [FK_T_EVENT_BASE_T_REHAB_COURSE_EventBase]
GO

ALTER TABLE [AKUZ].[T_REHAB_COURSE] DROP COLUMN [EventBase]
GO

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[AKUZ].[T_EVENT_REHABILITATION_CARD]') AND name = N'UQ_T_EVENT_REHABILITATION_CARD_RehabCourse' and is_unique_constraint <> 1)
DROP INDEX [UQ_T_EVENT_REHABILITATION_CARD_RehabCourse] ON [AKUZ].[T_EVENT_REHABILITATION_CARD]
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[AKUZ].[T_EVENT_REHABILITATION_CARD]') AND name = N'UQ_T_EVENT_REHABILITATION_CARD_RehabCourse' and is_unique_constraint = 1)
ALTER TABLE [AKUZ].[T_EVENT_REHABILITATION_CARD] DROP CONSTRAINT [UQ_T_EVENT_REHABILITATION_CARD_RehabCourse]
IF  EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[AKUZ].[T_EVENT_REHABILITATION_CARD]') AND name = N'RehabCourse_UQ')
ALTER TABLE [AKUZ].[T_EVENT_REHABILITATION_CARD] DROP COLUMN [RehabCourse_UQ]
GO

ALTER TABLE [AKUZ].[T_EVENT_REHABILITATION_CARD]ADD [RehabCourse_UQ] AS (CASE WHEN [RehabCourse] IS NOT NULL THEN NULL ELSE [EventRehabilitationCardID] END)
GO
CREATE UNIQUE NONCLUSTERED INDEX [UQ_T_EVENT_REHABILITATION_CARD_RehabCourse] ON [AKUZ].[T_EVENT_REHABILITATION_CARD] ([RehabCourse] ASC, [RehabCourse_UQ] ASC) ON [PRIMARY]
GO


