Note; this trigger only works on v7.x (and lower).
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO If EXISTS(Select [Name] from sysobjects where xType = 'TR' and [Name] = '_as_ItemGroups') Drop Trigger _as_ItemGroups Go -- ============================================= -- Author: Asamco BV, Alexander Toufexis -- Create date: 23/03/2020 -- Description: Trigger will block any items being created without a group (note; second trigger for INSERT part) -- ============================================= CREATE TRIGGER [dbo].[_as_ItemGroups] ON [dbo].[StkItem] AFTER UPDATE AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- DECLARES: DECLARE @ItemID int DECLARE @GroupID int DECLARE @ItemCode varchar(100) DECLARE @ItemName varchar(100) DECLARE @Message varchar(500) DECLARE @DeletedCount as float IF (UPDATE(ItemGroup)) BEGIN -- Insert statements for trigger here SELECT @ItemID = StockLink, @GroupID = ItemGroup, @ItemCode = Code, @ItemName = inserted.Description_1 FROM Inserted DECLARE @isERROR bit SET @isERROR = 0 IF (COALESCE(@GroupID,0) = 0) BEGIN SET @isERROR = 1 SET @Message = 'No Group was selected for Item (' + @ItemCode + ' - ' + @ItemName + '). ' END IF (@isERROR = 1) BEGIN RaisError(@Message, 16, 2); --select @isERROR = 1 END END --IF (UPDATE(ItemGroup)) END
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO If EXISTS(Select [Name] from sysobjects where xType = 'TR' and [Name] = '_as_ItemGroups_OnInsert') Drop Trigger _as_ItemGroups_OnInsert Go -- ============================================= -- Author: Asamco BV, Alexander Toufexis -- Create date: 23/03/2020 -- Description: Trigger will block any items being created without a group -- Note: not "multi-create" supported properly. (all items would be blocked) -- ============================================= CREATE TRIGGER [_as_ItemGroups_OnInsert] ON dbo.StkItem INSTEAD OF INSERT AS BEGIN SET NOCOUNT ON; /*Technical note: using "instead of insert", because the creation of stock items is done using a direct insert, without proper roll-back code around it. As such, we need to do it this way. */ select * into #tmp from inserted; declare @Msg varchar(1000) IF EXISTS(SELECT * FROM inserted i where COALESCE(i.ItemGroup,'') = '') BEGIN SET @Msg = 'No group was selected for the item(s). Creation of item(s) cancelled.' RAISERROR(@Msg,16,1); END ELSE BEGIN --NOTE: row nr not properly updated, so in case of multiple inserts at the same time, this will cause an issue. to solve, make sure you get the "row_number" part working. ALTER TABLE #tmp DROP COLUMN StockLink; --TO DO: change to stock table ID. (StockLink) insert into dbo.StkItem select * from #tmp; drop table #tmp; END END