IF NOT EXISTS(SELECT * FROM sys.tables (NOLOCK) WHERE name = 'CampaignCodesPeriod')
BEGIN
	CREATE TABLE [dbo].[CampaignCodesPeriod](
		[FK_CampaignCode] [smallint] NOT NULL,
		[PeriodType] [smallint] NOT NULL,
		[FromDate] [datetime] NOT NULL,
		[ToDate] [datetime] NOT NULL,
	 CONSTRAINT [PK_CampaignCodesPeriod] PRIMARY KEY CLUSTERED 
	(
		[FK_CampaignCode] ASC,
		[PeriodType] ASC,
		[FromDate] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[CampaignCodesPeriod]  WITH CHECK ADD  CONSTRAINT [FK_CampaignCodesPeriod_CampaignCode] FOREIGN KEY([FK_CampaignCode])
	REFERENCES [dbo].[CampaignCodes] ([PK_CampaignCode])

	ALTER TABLE [dbo].[CampaignCodesPeriod] CHECK CONSTRAINT [FK_CampaignCodesPeriod_CampaignCode]
	
	DECLARE @CampaignCode INT
	DECLARE @FromDate DATETIME
	DECLARE @ToDate DATETIME
	DECLARE @BookingFromDate DATETIME
	DECLARE @BookingToDate DATETIME
	DECLARE @SQL VARCHAR(max)

	SET @SQL = 'DECLARE db_cur CURSOR FOR SELECT PK_CampaignCode, FromDate, ToDate, BookingFromDate, BookingToDate
		FROM CampaignCodes WITH (NOLOCK)'
	
	EXEC(@SQL)
		
	OPEN db_cur
	FETCH NEXT FROM db_cur INTO @CampaignCode, @FromDate, @ToDate, @BookingFromDate, @BookingToDate

	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF (@FromDate IS NOT NULL) AND (@ToDate IS NOT NULL)
			INSERT INTO CampaignCodesPeriod	(FK_CampaignCode, PeriodType, FromDate, ToDate)
				VALUES (@CampaignCode, 0, @FromDate, @ToDate)
		IF (@BookingFromDate IS NOT NULL) AND (@BookingToDate IS NOT NULL)
			INSERT INTO CampaignCodesPeriod	(FK_CampaignCode, PeriodType, FromDate, ToDate)
				VALUES (@CampaignCode, 1, @BookingFromDate, @BookingToDate)
		FETCH NEXT FROM db_cur INTO @CampaignCode, @FromDate, @ToDate, @BookingFromDate, @BookingToDate
	END

	CLOSE db_cur
	DEALLOCATE db_cur

	ALTER TABLE [dbo].[CampaignCodes]
    DROP 
        COLUMN FromDate,
        COLUMN ToDate,
        COLUMN BookingFromDate,
		COLUMN BookingToDate

	ALTER TABLE [dbo].[CampaignCodes]
		REBUILD
END