IF EXISTS (SELECT * FROM dbo.SysObjects WHERE id = object_id(N'dbo.TransactionAfterInsert') AND OBJECTPROPERTY(id, N'IsTrigger') = 1) DROP TRIGGER dbo.TransactionAfterInsert 
GO
CREATE TRIGGER TransactionAfterInsert ON Transactions AFTER INSERT AS 
SET NOCOUNT ON

DECLARE @UseCashBox BIT

SELECT @UseCashBox = CONVERT(BIT, KeyValue) FROM HotelSetup(NOLOCK) WHERE Searchkey = 'FiscalPrinterSweden'
SET @UseCashBox = ISNULL(@UseCashBox,0)

IF @UseCashBox = 1
BEGIN
  DECLARE @UserTypeNumber TINYINT
  DECLARE @SystemCashBox INT
  DECLARE @UserIdNumber INT
  DECLARE @TransactionNumber INT

  SELECT @UserIdNumber = UserIdNumber, @TransactionNumber = TransactionNumber
  FROM inserted

  SELECT @SystemCashBox = PK_CashBox FROM CashBox (NOLOCK) WHERE Name = 'System'
  IF ISNULL(@SystemCashBox, 0) = 0
    SELECT TOP 1 @SystemCashBox = PK_CashBox FROM CashBox (NOLOCK)

  SELECT @UserTypeNumber = UserTypeNumber FROM Personel (NOLOCK) WHERE UserIDNumber = @UserIdNumber

  IF (@UserTypeNumber NOT IN (0,1,2)) -- utNotDefined, utOrdinary, utSystem, utAutoDay, utAutoNight, utPicassoOnline, utPierre, utHotel
    AND (NOT EXISTS(SELECT * FROM TransactionsRelation(NOLOCK) WHERE FK_TransactionNumber = @TransactionNumber))
  BEGIN
    INSERT INTO TransactionsRelation VALUES (@TransactionNumber, @SystemCashBox)
  END
END
