USE [Database]

IF OBJECT_ID('[Tables].[trg_insert_product_outflow_records]', 'TR') IS NOT NULL
  DROP TRIGGER [Tables].[trg_insert_product_outflow_records];
GO
CREATE TRIGGER [Tables].[trg_insert_product_outflow_records] ON [Tables].[product_outflow_records] AFTER INSERT
AS
  IF NOT EXISTS(
   SELECT *
   FROM [inserted] AS [i]
   JOIN [Tables].[product_values] AS [pv]
     ON [pv].[id] = [i].[barcode_product_value_id]
   JOIN [Tables].[price_history_records] AS [phr]
     ON [phr].[product_id] = [pv].[product_id]
  )
  BEGIN
    ROLLBACK TRANSACTION;
	RETURN;
  END
  DECLARE @barcode_attribute_id AS INT;
  SET @barcode_attribute_id = (
    SELECT [id]
    FROM [Tables].[attributes]
    WHERE [name] = 'Barcode'
  );
  DECLARE @stocks AS INT;
  SET @stocks  = (
    SELECT [Functions].[product_with_barcode_stock](@barcode_attribute_id, [barcode_product_value_id])
    FROM [inserted]
  );
  IF @stocks < 0
  BEGIN
    ROLLBACK TRANSACTION;
	RETURN;
  END
GO