I work with SQL Server 2008 R2
I have a simple trigger
CREATE TRIGGER [dbo].[T_Personne_ITrig] ON [dbo].[Personne] FOR INSERT AS
BEGIN
SET NOCOUNT ON
insert into syn_HistoriquePersonne
(hpers_Timestamp, Supprime, ID, Nom, Prenom, Champ1,
Champ2, Champ3, Champ4 SiteAssocie)
select GETDATE(), 0, ID, Nom, Prenom, Champ1, Champ2, Champ3,
Champ4, SiteAssocie
from inserted
END
It works properly. Problem is, I work on a program with an horrible code base so my boss don’t want to trigger to ever cause a rollback on the table Personne even if it fails. I know it’s really improbable, but he’s scared of timeout in case of huge database activity… ANYWAY
So I searched about committing in triggers. And changed the trigger to :
CREATE TRIGGER [dbo].[T_Personne_ITrig] ON [dbo].[Personne] FOR INSERT AS
BEGIN
SET NOCOUNT ON
COMMIT
insert into syn_HistoriquePersonne
(hpers_Timestamp, Supprime, ID, Nom, Prenom, Champ1,
Champ2, Champ3, Champ4 SiteAssocie)
select GETDATE(), 0, ID, Nom, Prenom, Champ1, Champ2, Champ3,
Champ4, SiteAssocie
from inserted
END
But the trigger kept shooting message
Transaction stopped in trigger, batch aborted.
So I made it like that :
CREATE TRIGGER [dbo].[T_Personne_ITrig] ON [dbo].[Personne] FOR INSERT AS
BEGIN
SET NOCOUNT ON
COMMIT
BEGIN TRAN
insert into syn_HistoriquePersonne
(hpers_Timestamp, Supprime, ID, Nom, Prenom, Champ1,
Champ2, Champ3, Champ4, SiteAssocie)
select GETDATE(), 0, ID, Nom, Prenom, Champ1, Champ2, Champ3,
Champ4, SiteAssocie
from inserted
END
It stopped doing the batch aborted, but it seems to never insert anything in my historic table… I read about the subject and this should work I think. But it doesn’t…
Anyone else already had that problem and how can I fix that?
I am doing simple insert into to test my trigger.
Unfortunately you’re barking up the wrong tree. You can’t play with transactions in that way.
If the only concern was failed inserts, you could simply code a check around your insert. Or just be very throrough in ensuring the constraints on your table accurately reflect it’s use. But, as you’re also concerned about the duration of the process causing a command time-out, this won’t cover you entirely (in fact it’ll make that time-out very slightly more likely).
The only approach that I can see working is to massively simplify the insert statement, and insert something (all the data, or just the timestamp and id?) into a holding table which has no constraints, or indexes. You would then need a server side process that is called repeatedly to process your holding table.
As your case seems to be just maintaining a historic log, perhaps an option could be as simple as removing all constraints from the historique table. All the solutions are a bit dirty, but then the requirement from your boss seems a bit unusual; the answer should really be capacity planning in my opinion.
I don’t know if that fits with your real world scenario, but I hope it helps.