-- create table
CREATE TABLE [AKUZ].[T_RESOURCE_QUOTA_LINK]
(
    [ResourceQuotaLinkID] uniqueidentifier NOT NULL,
    [WeekType] int NOT NULL,
    [DayType] int NOT NULL,
    [Resource] uniqueidentifier NOT NULL,
    ResourceScheduleID uniqueidentifier NOT NULL
)
ON [PRIMARY]
GO

ALTER TABLE [AKUZ].[T_RESOURCE_QUOTA_LINK] ADD CONSTRAINT [PK_T_RESOURCE_QUOTA_LINK]
PRIMARY KEY CLUSTERED ([ResourceQuotaLinkID]) ON [PRIMARY]
GO

ALTER TABLE [AKUZ].[T_RESOURCE_QUOTA_LINK] ADD CONSTRAINT [FK_T_RESOURCE_T_RESOURCE_QUOTA_LINK_Resource]
FOREIGN KEY([Resource]) REFERENCES [AKUZ].[T_RESOURCE] ([ResourceID])
GO

-- insert table
insert into [AKUZ].[T_RESOURCE_QUOTA_LINK]([ResourceQuotaLinkID],[WeekType],[DayType],[Resource],ResourceScheduleID)
select newid(),[WeekType],[DayType],[Resource],ResourceScheduleID from AKUZ.T_RESOURCE_SCHEDULE


-- alter table

ALTER TABLE [AKUZ].[T_RESOURCE_QUOTA] ADD [ResourceQuotaLink] uniqueidentifier NULL
GO
UPDATE rq
SET [ResourceQuotaLink] = l.[ResourceQuotaLinkID]
from [AKUZ].[T_RESOURCE_QUOTA] rq
	join [AKUZ].[T_RESOURCE_QUOTA_LINK] l on rq.ResourceSchedule = l.ResourceScheduleID
GO
ALTER TABLE [AKUZ].[T_RESOURCE_QUOTA] ALTER COLUMN [ResourceQuotaLink] uniqueidentifier NOT NULL
GO

ALTER TABLE [AKUZ].[T_RESOURCE_QUOTA] ADD CONSTRAINT [FK_T_RESOURCE_QUOTA_LINK_T_RESOURCE_QUOTA_ResourceQuotaLink]
FOREIGN KEY([ResourceQuotaLink]) REFERENCES [AKUZ].[T_RESOURCE_QUOTA_LINK] ([ResourceQuotaLinkID])
GO

ALTER TABLE [AKUZ].[T_RESOURCE_QUOTA_LINK] drop column ResourceScheduleID
GO

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[AKUZ].[FK_T_RESOURCE_SCHEDULE_T_RESOURCE_QUOTA_RESOURCESCHEDULE]') AND parent_object_id = OBJECT_ID(N'[AKUZ].[T_RESOURCE_QUOTA]'))
ALTER TABLE [AKUZ].[T_RESOURCE_QUOTA] DROP CONSTRAINT [FK_T_RESOURCE_SCHEDULE_T_RESOURCE_QUOTA_RESOURCESCHEDULE]
GO


IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[AKUZ].[T_RESOURCE_QUOTA]') AND name = N'UQ_T_RESOURCE_QUOTA_ResourceSchedule')
DROP INDEX [UQ_T_RESOURCE_QUOTA_ResourceSchedule] ON [AKUZ].[T_RESOURCE_QUOTA]
GO


ALTER TABLE [AKUZ].[T_RESOURCE_QUOTA] DROP COLUMN [ResourceSchedule]
GO


-- trigger


IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[AKUZ].[RESOURCE_SCHEDULE_Unique]'))
DROP TRIGGER [AKUZ].[RESOURCE_SCHEDULE_Unique]
GO


