SQL Server trigger firing 3 times - sql-server

I have set up the following audit trigger to create copies of the record changes into my change log (should we ever need to see what happened to our data). The problem is every time I update the record, it creates 3 records in my log table.
Below you can see the result set and my code I have been using.
Code:
/* ==Scripting Parameters==
Source Server Version : SQL Server 2016 (13.0.4446)
Source Database Engine Edition : Microsoft SQL Server Standard Edition
Source Database Engine Type : Standalone SQL Server
Target Server Version : SQL Server 2017
Target Database Engine Edition : Microsoft SQL Server Standard Edition
Target Database Engine Type : Standalone SQL Server
*/
USE [STONE_DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[tr_set_for_update_audit_fields]
ON [dbo].[permission_types]
FOR UPDATE
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO STONE_DB_CHANGE_LOGS.dbo.permission_types_log ([permission_type_id], [business_process], [active], [created_at], [created_by], [change_type], [change_user], [change_at])
SELECT DISTINCT
inserted.id,
inserted.[business_process], inserted.[active],
inserted.[created_at], inserted.[created_by],
'U', SYSTEM_USER, GETDATE()
FROM
inserted
WHERE
1 = 1
AND inserted.[created_at] < getdate();
UPDATE [dbo].[permission_types]
SET updated_at = GETDATE(), updated_by = SYSTEM_USER
FROM [dbo].[permission_types]
INNER JOIN inserted ON permission_types.id = inserted.id
WHERE 1 = 1
--AND permission_types.updated_at < getdate()
;
PRINT 'Record Updated'
END

You need to prevent a database trigger from recursing
Check this solution
How do I prevent a database trigger from recursing?

You should add at the begin of trigger code like this:
IF NOT UPDATE(business_process)
RETURN;
More info: UPDATE()

USE the following code to avoid nesting
IF((SELECT trigger_nestlevel() ) > 1)
RETURN

Related

Convert SQL Server trigger to Oracle and master.dbo.sysprocesses - not duplicate

I tried searching but could not find exactly what I'm looking for. I'm new to SQl Server and involved into SQL Server to Oracle conversion, and it is manual conversion. All I have is SQL Server files.
I see two types of SQL Server triggers - FOR UPDATE and FOR INSERT. They look to me as before update and before insert triggers in Oracle. I'd like to confirm this please and if you can provide examples that would be great.
Also, what is the equivalent to master.dbo.sysprocesses in Oracle please? Is this v$session? I can get user from dual in Oracle. Is this what nt_username is in below code?
Here is typical code examples I need to convert to Oracle - is this before insert?
CREATE TRIGGER trigger_name ON dbo.table_name
FOR Insert AS
declare #InsertUser varchar(32)
BEGIN
SELECT #InsertUser = nt_username from master.dbo.sysprocesses where spid = ##spid
Update table_name
SET dCreateDate = GETDATE(), cCreateUser = #InsertUser
FROM table1 a ,table2 i WHERE a.tab_id = i.tab_id
END
GO
Update Trigger - before update?
CREATE TRIGGER trigger_name ON dbo.table_name
FOR UPDATE AS
declare #UpdateUser varchar(32)
if not update(CreateUser) and not update(CreateDate)
BEGIN
SELECT #UpdateUser = nt_username from master.dbo.sysprocesses where spid = ##spid
Update table_name
SET UpdateDate = GETDATE(), UpdateUser = #UpdateUser
FROM table1 a ,table2 i WHERE a.tab_id = i.tab_id
END
GO
Should I combine these two into if inserting... elsif updating in Oracle?
Thank you very much to all.

Trigger syntax for sql server

I have realized that the syntax for triggers is slightly different for different software. What would be the syntax for the following piece of code in SQL Server 2012?
Create trigger before_playercatalogue_update
before update
on player_catalogue
For each row
Begin
Insert into player_audit
set action = 'update',
playerid = old.playerid
fname = old.fname,
datachange = (Now);
End
The syntax is quite different. It would look like:
Create trigger after_playercatalogue_update
on player_catalogue after update
as
Begin
Insert into player_audit(action, playerid, fname, datachange)
select 'update', playerid, fname, getdate()
from inserted;
End;
Note some of the changes:
This is an after trigger. SQL Server doesn't have "before" triggers.
The set clause is not supported for insertin SQL Server (or other databases).
SQL Server does not have "new" and "old". It uses inserted, a view on the records that have changed.

The multi-part identifier "inserted.Id" could not be bound while creating trigger

I am trying to create a trigger on a table in SQL Server 2012, but it is giving an error like below
"The multi-part identifier "inserted.Id" could not be bound",
The query I am executing is
CREATE TRIGGER dbo.[TR_t_documents_InsertUpdateDelete] ON
dbo.[t_documents] AFTER INSERT, UPDATE, DELETE
AS
BEGIN
UPDATE dbo.[t_documents]
SET dbo.[t_documents].[UpdatedAt] = CONVERT(DATETIMEOFFSET, SYSUTCDATETIME())
FROM
INSERTED
WHERE inserted.[Id] = dbo.[t_documents].[Id]
END
The same is executing successfully in SQL Server 2014.
Can anyone help me why this is happening in SQL server 2012?
This is due to the collation you have for the database. In this case, you are using a case sensitive collation, so the table names need to be consistently. For the virtual trigger tables, these need to be in upper case, for example:
CREATE TRIGGER dbo.[TR_t_documents_InsertUpdateDelete] ON
dbo.[t_documents] AFTER INSERT, UPDATE, DELETE
AS
BEGIN
UPDATE dbo.[t_documents]
SET dbo.[t_documents].[UpdatedAt] = CONVERT(DATETIMEOFFSET, SYSUTCDATETIME())
FROM
INSERTED
WHERE INSERTED.[Id] = dbo.[t_documents].[Id]
-- ^^^^^^^^
-- THIS!
END

Testing linked server conccetion inside trigger or procedure

I wrote a trigger that updates local table and similar table on linked server.
CREATE TRIGGER myTtableUpdate ON myTable
AFTER UPDATE
AS
IF (COLUMNS_UPDATED() > 0)
BEGIN
DECLARE #retval int;
BEGIN TRY
EXEC #retval = sys.sp_testlinkedserver N'my_linked_server';
END TRY
BEGIN CATCH
SET #retval = sign(##error);
END CATCH;
IF (#retval = 0)
BEGIN
UPDATE remoteTable SET remoteTable.datafield = i.datafield
FROM my_linked_server.remote_database.dbo.myTable remoteTable
INNER JOIN inserted i ON (remoteTable.id = i.id)
END
END -- end of trigger
Unfortunately when connection is down I get error message
'Msg 3616, Level 16, State 1, Line 2'
'Transaction doomed in trigger. Batch has been aborted'
and locally made update is rolled back.
Is there a way to maintain this error and keep local updates?
Note that I'm using SQL Server 2005 Express Edition on both PCs running Windows XP Pro.
edit1: SQL server is Express Edition
edit2: Both PCs run Windows XP Pro so these aren't servers
don't write to the remote server in the trigger.
create a local table to store rows that need to be pushed to the remote server
insert into this new local table in the trigger
create a job that runs every N minutes to insert from this local table into remote server.
this job can run a procedure that can test for the connection, and when it is back up, it will handle all rows in the new local table. It can process the rows in the local table this way:
declare #OutputTable table (RowID int not null)
insert into my_linked_server.remote_database.dbo.myTable remoteTable(...columns...)
OUTPUT INSERTED.RowID
INTO #OutputTable
SELECT ...columns...
from NewLocalTable
delete NewLocalTable
from NewLocalTable n
inner join #OutputTable o ON n.RowID=o.RowID
EDIT based OP comment
after inserting into this new local table start the job from the trigger (sp_start_job), it will run in its own scope. If you can't use sql server jobs, use xp_cmdshell to execute the stored procedure (lookup SQLCMD or ISQL or OSQL, I'm not sure what you have). still schedule the job every N minutes, so it will eventually run when the connection comes up.
Is at least one of the servers Workgroup edition or higher? You can use Service Broker to ship your records instead of linked servers, but it will not work between to Express editions due to licensing restrictions. Is a solution relying exclusively on SQL, offers reliability in case of incidents (one of the servers is unavailable) and your updates will propagate in real time (as soon as they are committed). My site has many examples on how to do this, you can start with this article here on how to achieve high message throughput.

What is the most portable way to check whether a trigger exists in SQL Server?

I'm looking for the most portable method to check for existence of a trigger in MS SQL Server. It needs to work on at least SQL Server 2000, 2005 and preferably 2008.
The information does not appear to be in INFORMATION_SCHEMA, but if it is in there somewhere, I would prefer to use it from there.
I do know of this method:
if exists (
select * from dbo.sysobjects
where name = 'MyTrigger'
and OBJECTPROPERTY(id, 'IsTrigger') = 1
)
begin
end
But I'm not sure whether it works on all SQL Server versions.
There's also the preferred "sys.triggers" catalog view:
select * from sys.triggers where name = 'MyTrigger'
or call the sp_Helptrigger stored proc:
exec sp_helptrigger 'MyTableName'
But other than that, I guess that's about it :-)
Marc
Update (for Jakub Januszkiewicz):
If you need to include the schema information, you could also do something like this:
SELECT
(list of columns)
FROM sys.triggers tr
INNER JOIN sys.tables t ON tr.parent_id = t.object_id
WHERE t.schema_id = SCHEMA_ID('dbo') -- or whatever you need
This works on SQL Server 2000 and above
IF OBJECTPROPERTY(OBJECT_ID('{your_trigger}'), 'IsTrigger') = 1
BEGIN
...
END
Note that the naive converse doesn't work reliably:
-- This doesn't work for checking for absense
IF OBJECTPROPERTY(OBJECT_ID('{your_trigger}'), 'IsTrigger') <> 1
BEGIN
...
END
...because if the object doesn't exist at all, OBJECTPROPERTY returns NULL, and NULL is (of course) not <> 1 (or anything else).
On SQL Server 2005 or later, you could use COALESCE to deal with that, but if you need to support SQL Server 2000, you'll have to structure your statement to deal with the three possible return values: NULL (the object doesn't exist at all), 0 (it exists but is not a trigger), or 1 (it's a trigger).
Assuming it is a DML trigger:
IF OBJECT_ID('your_trigger', 'TR') IS NOT NULL
BEGIN
PRINT 'Trigger exists'
END
ELSE
BEGIN
PRINT 'Trigger does not exist'
END
For other types of objects (tables, views, keys, whatever...), see: http://msdn.microsoft.com/en-us/library/ms190324.aspx under 'type'.
Tested and doesn't work on SQL Server 2000:
select * from sys.triggers where name = 'MyTrigger'
Tested and works ok on SQL Server 2000 and SQL Server 2005:
select * from dbo.sysobjects
where name = 'MyTrigger' and OBJECTPROPERTY(id, 'IsTrigger')
In addition to the excellent answer by marc_s:
if the existence check is intended prior to dropping or modifying the trigger in some way, use a direct TSQL try/Catch bock, as the fastest means.
For instance:
BEGIN TRY
DROP TRIGGER MyTableAfterUpdate;
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS erno WHERE erno = 3701; -- may differ in SQL Server < 2005
END CATCH;
The Error Message will be
Cannot drop the trigger 'MyTableAfterUpdate', because it does not exist or you do not have permission.
Then simply check if the Executed Result returned rows or not, which is easy in direct sql as well as the programmatic APIs (C#,...).
If you're trying to find a server scoped DDL Trigger on SQL Server 2014, you should try sys.server_triggers.
IF EXISTS (SELECT * FROM sys.server_triggers WHERE name = 'your trigger name')
BEGIN
{do whatever you want here}
END
If I told tou anything incorrect, please let me know.
Edit:
I didn't check for this dm on another versions of SQL Server.
Are trigger names forced to be unique in SQL server?
As triggers are by definition applied to a specific table would it not be more efficient to restrict the search to only the table in question?
We have a database with over 30k tables in it all of which have at least one trigger and may have more (bad DB design - quite probably, but it made sense years ago and didn't scale well)
I use
SELECT * FROM sys.triggers
WHERE [parent_id] = OBJECT_ID(#tableName)
AND [name] = #triggerName
I would use this syntax to check and drop trigger
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SCHEMA_NAME].[TRIGGER_NAME]') AND type in (N'TR'))
DROP TRIGGER [SCHEMA_NAME].[TRIGGER_NAME]
Generated by Sql Server Management Studio:
IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[RolesYAccesos2016_UsuariosCRM_trgAfterInsert]'))
DROP TRIGGER [dbo].[RolesYAccesos2016_UsuariosCRM_trgAfterInsert]
GO
CREATE TRIGGER [dbo].[RolesYAccesos2016_UsuariosCRM_trgAfterInsert]
ON [PortalMediadores].[dbo].[RolesYAccesos2016.UsuariosCRM]
FOR INSERT
AS
...
For select ##version
Microsoft SQL Server 2008 R2 (RTM) - 10.50.1797.0 (X64) Jun 1 2011
15:43:18 Copyright (c) Microsoft Corporation Enterprise Edition
(64-bit) on Windows NT 6.1 (Build 7601: Service Pack 1)
(Hypervisor)

Resources