IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[IdentityInvoice]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
  CREATE TABLE [dbo].[IdentityInvoice]
  (
    [DBTableName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    [HotelCustomerNumber] [INT] NOT NULL ,
    [FkDepartment] [smallint] NOT NULL ,
    [IdentityField] [int] NOT NULL ,
    CONSTRAINT [PK_IdentityInvoice] PRIMARY KEY CLUSTERED
    (
      [DBTableName],
      [HotelCustomerNumber],
      [FkDepartment]
    )  ON [PRIMARY]
  ) ON [PRIMARY]

  ALTER TABLE [dbo].[IdentityInvoice] ADD  CONSTRAINT [DF_IdentityInvoice_FkDepartment]  DEFAULT ((-1)) FOR [FkDepartment]
  
  INSERT INTO IdentityInvoice 
    SELECT DBTableName, HotelCustomerNumber, FkDepartment, IdentityField FROM IdentityFields 
    WHERE DbTableName = 'BILLIDENTITY' OR DbTableName = 'INVOICEIDENTITY' OR DbTableName = 'FOLIOIDENTITY'
  IF (SELECT COUNT(*) FROM IdentityInvoice (NOLOCK)) > 0 
    DELETE IdentityFields WHERE DbTableName = 'BILLIDENTITY' OR DbTableName = 'INVOICEIDENTITY' OR DbTableName = 'FOLIOIDENTITY'
END
