IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[PersonelHotelXTab]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
  CREATE TABLE [dbo].[PersonelHotelXTab](
    [FK_UserIdNumber] [int] NOT NULL,
    [FK_HotelCustomerNumber] [int] NOT NULL,
    CONSTRAINT [PK_PersonelHotelXTab] PRIMARY KEY CLUSTERED 
    (
	    [FK_UserIdNumber] ASC,
	    [FK_HotelCustomerNumber] ASC
    )
  ) ON [PRIMARY]

  ALTER TABLE [dbo].[PersonelHotelXTab]  WITH NOCHECK ADD  CONSTRAINT [FK_PersonelHotelXTab_Customer] FOREIGN KEY([FK_HotelCustomerNumber])
  REFERENCES [dbo].[Customer] ([CustomerNumber])

  ALTER TABLE [dbo].[PersonelHotelXTab] CHECK CONSTRAINT [FK_PersonelHotelXTab_Customer]

  ALTER TABLE [dbo].[PersonelHotelXTab]  WITH NOCHECK ADD  CONSTRAINT [FK_PersonelHotelXTab_Personel] FOREIGN KEY([FK_UserIdNumber])
  REFERENCES [dbo].[PERSONEL] ([UserIDNumber])

  ALTER TABLE [dbo].[PersonelHotelXTab] CHECK CONSTRAINT [FK_PersonelHotelXTab_Personel]
END

IF NOT EXISTS (SELECT * FROM PersonelHotelXTab WITH (NOLOCK))
BEGIN
  INSERT INTO PersonelHotelXTab (FK_UserIdNumber, FK_HotelCustomerNumber)
  SELECT DISTINCT Personel.UserIdNumber, Customer.CustomerNumber
  FROM Personel WITH (NOLOCK)
  INNER JOIN PersonelDepartmentsXtab WITH (NOLOCK) ON PersonelDepartmentsXtab.UserIdNumber = Personel.UserIdNumber
  INNER JOIN Departments WITH (NOLOCK) ON Departments.PK_Department = PersonelDepartmentsXtab.FK_Department
  INNER JOIN Customer WITH (NOLOCK) ON Customer.HotelNumber = Departments.HotelNumber
    AND Customer.CustomerTypeNumber = 7
    AND Customer.HotelNumber >= 0 
    AND ISNULL(Customer.MarkAsDeleted, 0) = 0
END