IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[CampaignCodesTicketXTab]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
  CREATE TABLE [dbo].[CampaignCodesTicketXTab]
  (
    [FK_CampaignCode] [smallint] NOT NULL,
    [FK_ArrangementLineUniqueID] [int] NOT NULL,
    [TimesUsed] [smallint] NOT NULL,
    CONSTRAINT [PK_CampaignCodesTicketXTab] PRIMARY KEY CLUSTERED
    (
      [FK_CampaignCode] ASC,
      [FK_ArrangementLineUniqueID] ASC
    )
  ) ON [PRIMARY]

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

  ALTER TABLE [dbo].[CampaignCodesTicketXTab] CHECK CONSTRAINT [FK_CampaignCodesTicketXTab_CampaignCode]

END

IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_CampaignCodesTicketXTab_ArrangementLineUniqueID]') AND parent_object_id = OBJECT_ID(N'[dbo].[CampaignCodesTicketXTab]'))
ALTER TABLE [dbo].[CampaignCodesTicketXTab]  DROP CONSTRAINT [FK_CampaignCodesTicketXTab_ArrangementLineUniqueID]


IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_CampaignCodesTicketXTab_ArrangementLines]') AND parent_object_id = OBJECT_ID(N'[dbo].[CampaignCodesTicketXTab]'))
ALTER TABLE [dbo].[CampaignCodesTicketXTab]  WITH CHECK ADD  CONSTRAINT [FK_CampaignCodesTicketXTab_ArrangementLines] FOREIGN KEY([FK_ArrangementLineUniqueID])
REFERENCES [dbo].[ArrangementLines] ([ArrangementLineUniqueID])
GO

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_CampaignCodesTicketXTab_ArrangementLines]') AND parent_object_id = OBJECT_ID(N'[dbo].[CampaignCodesTicketXTab]'))
ALTER TABLE [dbo].[CampaignCodesTicketXTab] CHECK CONSTRAINT [FK_CampaignCodesTicketXTab_ArrangementLines]
GO

IF NOT EXISTS
(
  SELECT SysColumns.Name
  FROM SysObjects WITH (NOLOCK)
    INNER JOIN SysColumns WITH (NOLOCK) ON SysColumns.Id = SysObjects.ID
    AND SysColumns.Name = 'TicketNumberOfDays'
    WHERE SysObjects.Name = 'CampaignCodes'
)
BEGIN
  ALTER TABLE CampaignCodes ADD TicketNumberOfDays SMALLINT NULL
END
GO

IF NOT EXISTS
(
  SELECT SysColumns.Name
  FROM SysObjects WITH (NOLOCK)
    INNER JOIN SysColumns WITH (NOLOCK) ON SysColumns.Id = SysObjects.ID
    AND SysColumns.Name = 'TicketNumberOfTimes'
    WHERE SysObjects.Name = 'CampaignCodes'
)
BEGIN
  ALTER TABLE CampaignCodes ADD TicketNumberOfTimes SMALLINT NULL
END
GO



