I have the following trigger (along with others in similar tables) that sometimes cannot put data in a historical table. It should put the data in the historical table in the same way as it is inserted / updated and marked with a date.
CREATE TRIGGER [dbo].[trig_UpdateHistoricProductCustomFields] ON [dbo].[productCustomFields] AFTER UPDATE,INSERT AS BEGIN IF ((UPDATE(data))) BEGIN SET NOCOUNT ON; DECLARE @date bigint SET @date = datepart(yyyy,getdate())*10000000000+datepart(mm,getdate())*100000000+datepart(dd,getdate())*1000000+datepart(hh,getdate())*10000+datepart(mi,getdate())*100+datepart(ss,getdate()) INSERT INTO historicProductCustomFields (productId,customFieldNumber,data,effectiveDate) (SELECT productId,customFieldNumber,data,@date from inserted) END END
Scheme:
CREATE TABLE [dbo].[productCustomFields]( [id] [int] IDENTITY(1,1) NOT NULL, [productId] [int] NOT NULL, [customFieldNumber] [int] NOT NULL, [data] [varchar](50) NULL, CONSTRAINT [PK_productCustomFields] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] CREATE TABLE [dbo].[historicProductCustomFields]( [id] [bigint] IDENTITY(1,1) NOT NULL, [productId] [int] NOT NULL, [customFieldNumber] [int] NOT NULL, [data] [varchar](50) NULL, [effectiveDate] [bigint] NOT NULL, CONSTRAINT [PK_historicProductCustomFields] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
I insert and update only one record at a time in the productCustomFields table. It seems to work in 99% of cases and is hard to check for failure. Can someone shed some light on what I can do wrong or better for this type of trigger?
The environment is Sql Server Express 2005. I have not yet posted the SQL Server Service Pack for this particular client.