IF EXISTS (SELECT * FROM dbo.SysObjects WHERE id = object_id(N'[dbo].[Invoices]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) AND
  NOT EXISTS (SELECT * FROM dbo.SysObjects WHERE id = object_id(N'[dbo].[Invoice]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
/*
  SELECT Count(*) FROM CanceledBillNumbers (NOLOCK) 
  SELECT Count(*) FROM Invoices WITH (NOLOCK)
  SELECT Count(*) FROM Transactions T WITH (NOLOCK) 
  WHERE T.ShowOnBillFlag = 1 and T.MovedDeleted = 0 and ISNULL(T.InvoiceBillNumber, 0) <> 0 and ISNULL(T.HotelCustomerNumber, -1) > 0
*/
  CREATE TABLE dbo.[Invoice](
		[PkInvoice] [int] IDENTITY (1, 1) NOT NULL,
		[FkCustomerHotel] [int] NOT NULL,
		[FkDepartment] [int] NOT NULL,
		[FkStaff] [int] NOT NULL,
		[FkBillLayout] [int] NULL,
		[BillNumber] [int] NULL,
		[InvoiceNumber] [int] NULL,
		[CreatedDate] [datetime] NOT NULL,
		[CancelDate] [datetime] NULL,
		[CopyPrinted] [bit] NULL,
		[Note] [nvarchar](MAX) NULL,
		[Picture] [image] NULL,
		[Report] [image] NULL,
		[FkInvoiceRelated] [int] NULL,
  	        [GiroId] [varchar](21) NULL,
	        [CreditorId] [varchar](8) NULL,
		[FkTemplate] [int] NULL,
		[FkCountry] [int] NULL,
		[ReceiptType] [smallint] NOT NULL,
		[ReceiptNumber] [int] NOT NULL,

  	  CONSTRAINT [PK_Invoice] PRIMARY KEY CLUSTERED 
	  (
		[PkInvoice] DESC
	  )
	) ON [PRIMARY]

  CREATE TABLE dbo.[InvoiceTransactionXTab](
		[FkInvoice] [int] NOT NULL,
		[FkTransaction] [int] NOT NULL,
  	  CONSTRAINT [PK_InvoiceTransactionXTab] PRIMARY KEY CLUSTERED 
	  (
		[FkInvoice] DESC,
		[FkTransaction] DESC
	  )
	) ON [PRIMARY]

  CREATE TABLE [dbo].[ReceiptFiscal](
	  [PkReceiptFiscal] [int] IDENTITY (1, 1) NOT NULL,
  	  [FkInvoice] [int] NOT NULL,
	  [CashId] [int] NULL,
	  [ExternalNumber] [varchar](50) NULL,
	  [ManufactIdFCU] [varchar](17) NULL,
	  [CashRegisterMarking] [varchar](16) NULL,
	  [Terminal] [varchar](50) NULL,
  CONSTRAINT [PK_ReceiptFiscal] PRIMARY KEY CLUSTERED 
  (
	  [PkReceiptFiscal] ASC
  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  ) ON [PRIMARY]
END
