/*

nb20171207 Created
Description
Create CashboxTerminalXTab  table if not exists
*/

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CashboxTerminalXTab]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
  CREATE TABLE [dbo].[CashboxTerminalXTab](
	[FkCashbox] int NOT NULL,
	[FkTerminal] int NOT NULL                
	
	CONSTRAINT [PK_CashboxTerminalXTab] PRIMARY KEY CLUSTERED 
	(
		[FkCashbox], [FkTerminal] ASC
	)
  )
GO
SET NOCOUNT ON
INSERT INTO CashboxTerminalXTab  
SELECT T.Fk_Cashbox, T.TerminalNumber
FROM Terminals T (NOLOCK) 
WHERE Fk_Cashbox > 0
EXCEPT
SELECT FkCashbox, FkTerminal FROM CashboxTerminalXTab
UPDATE Terminals SET Fk_CashBox = NULL where Fk_CashBox > 0
