USE [Database]

IF OBJECT_ID('[Tables].[trg_insert_product_write_off_records]', 'TR') IS NOT NULL
  DROP TRIGGER [Tables].[trg_insert_product_write_off_records];
GO
CREATE TRIGGER [Tables].[trg_insert_product_write_off_records] ON [Tables].[product_write_off_records] AFTER INSERT
AS
  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