I have several problems trying to resolve an SQL trigger in order to automatically set the user to lock and create a block record, including the date in another table, if their maturity date is equal to the set date.
The problem is that when the trigger is disabled by insertion, the print instructions are executed and the insertion occurs, but is there no insertion in the table or an update statement? Can someone explain why?
Note. The insert and update statements work fine when executed.
ACCOUNT TABLE
CREATE TABLE [dbo].[Account]( [AccountNo] [int] IDENTITY(1,1) NOT NULL, [CustomerNo] [int] NOT NULL, [PaymentNo] [int] NULL, [CreditNo] [int] NULL, [BlockID] [dbo].[number] NULL, [Balence] [dbo].[currency] NOT NULL, [AmountDue] [dbo].[currency] NOT NULL, [DueDate] [dbo].[dates] NULL, [AutherisedBy] [nvarchar](50) NOT NULL, [DateCreated] [date] NOT NULL,
BLOCKEDUSER table
CREATE TABLE [dbo].[BlockedUsers]( [BlockID] [int] IDENTITY(1,1) NOT NULL, [DateEnforced] [dbo].[dates] NOT NULL, [Blocked] [dbo].[switch] NOT NULL,
TRIGGER
ALTER TRIGGER [dbo].[Add_Blocked_User] ON [dbo].[Account] FOR INSERT AS BEGIN SET NOCOUNT ON; Declare @ID int Select @ID = [AccountNo] from inserted If(Select [DueDate] from inserted) = '2011-01-01' INSERT INTO dbo.BlockedUsers(DateEnforced,Blocked) VALUES (GETDATE(),1) PRINT 'New Block Date Added' UPDATE Account Set BlockID = IDENT_CURRENT('BlockID') where @ID = @ID PRINT 'Account Blocked' END GO
A fully working example: completed using the help below.
ALTER TRIGGER [dbo].[Add_Blocked_User] ON [dbo].[Account] AFTER INSERT AS BEGIN SET NOCOUNT ON; Declare @ID int Select @ID = [AccountNo] from inserted If(Select [DueDate] from inserted)Not Between (select CONVERT(date, getdate() - 30)) And (select CONVERT(date, getdate())) Begin INSERT INTO dbo.BlockedUsers(DateEnforced,Blocked) VALUES (GETDATE(),1) PRINT 'New Block Date Added' UPDATE Account Set BlockID = (Select Max(BlockID) From BlockedUsers) where [AccountNo] = (Select [AccountNo] from inserted) PRINT 'Account Blocked' End END GO