oracle triggers firing order (collision, and deadclock ) - database

I have 2 insert triggers, that fire on same table, they both try to alter table row content and then happens collision, or my sql developer starts endless execution of the commands, and then I need to restart DB. How to fix that? Should I merge those 2 triggers into 1 trigger? Or should try to control firing order with this command:
execute immediate 'alter trigger trigger_name disable';
execute immediate 'alter trigger trigger_name enable';
or should I use trigger inside of trigger.. please I want expert opinion about this one.. im in big dilema right now, since this is the first time I do PL/SQL coding.
EDIT: HERE ARE THE TRIGGERS WITH WHICH I WORK ON:
create or replace
TRIGGER TRG_PROCED_SN_INS_CENA
AFTER INSERT ON STAVKA_NARUDZBENICE
FOR EACH ROW
DECLARE
pragma autonomous_transaction;
sifra_narudzbenice NUMBER;
BEGIN
paket_sn_sifnar.sifra_narudzbenice := :NEW.sifra_narudzbenice;
pStavkaNarudzbeniceInsert(paket_sn_sifnar.sifra_narudzbenice);
COMMIT;
END;
/
create or replace
TRIGGER TRG_SN_INS_UPD_NAZIV
AFTER INSERT ON Stavka_narudzbenice
FOR EACH ROW
FOLLOWS TRG_PROCED_SN_INS_CENA
DECLARE
v_naziv_proizvoda VARCHAR2(25);
v_cena NUMBER;
BEGIN
SELECT naziv_proizvoda INTO v_naziv_proizvoda
FROM proizvod
WHERE sifra_proizvoda=:NEW.sifra_proizvoda;
SELECT cena INTO v_cena
FROM stavka_kataloga
WHERE sifra_proizvoda=:NEW.sifra_proizvoda;
UPDATE stavka_narudzbenice
SET naziv_proizvoda = v_naziv_proizvoda, cena = v_cena WHERE sifra_proizvoda =:NEW.sifra_proizvoda;
END;
/

In 11G you can control the order of triggers using the FOLLOWS clause. For example:
CREATE TRIGGER trg1
AFTER INSERT ON EMP
FOR EACH ROW
BEGIN
...
END;
CREATE TRIGGER trg2
AFTER INSERT ON EMP
FOR EACH ROW
FOLLOWS trg1
BEGIN
...
END;
i.e. There are 2 triggers trg1 and trg2 that both fire after insert on table EMP, and we have declared that trg2 should fire after (follow) trg1.

You can't control the order in which statement level triggers fire. Your best bet is to combine the two into one trigger. Even better, avoid the use of triggers if at all possible.

Related

"Instead of delete trigger" triggers two times

I am using MS SQL Server 2016 where I have implemented a instead of delete trigger. It looks like this:
ALTER TRIGGER MyTrigger ON MyTable INSTEAD OF DELETE AS
BEGIN
IF --some condition
BEGIN
RAISERROR ('Error msg', 16, 1)
ROLLBACK TRAN
RETURN
END
DELETE MyTable FROM MyTable JOIN deleted ON MyTable.id = deleted.id
END
If I execute a DELETE statement on the table 'MyTable' and the condition in the if is not fulfilled the DELETE statement is executed after the if-block. This is absolutely correct. But in the console of SSMS it is written twice that the DELETE statement was executed. So the following is written in the console:
(1 rows affected)
(1 rows affected)
I do not understand why. Why does SSMS indicate twice that a row is affected? I use SSMS version 15.0.18338.0.
This is because there were 2 sets of data effect, the set outside the TRIGGER, and then again inside it, because the initial dataset doesn't perform the DML operation itself. If you don't want to see the latter count, turn NOCOUNT to ON. This, of course, means that if fewer rows are effected in your TRIGGER, you won't know about it in the output from SSMS (but it's just informational anyway).
It is also heavily advised that you don't use ROLLBACK inside a TRIGGER, handle transactions outside the TRIGGER, not inside. RAISERROR isn't recommend either and you should be using THROW for new development work (that's been recommended since 2012!). This results in a TRIGGER like below:
CREATE OR ALTER TRIGGER MyTrigger ON dbo.MyTable INSTEAD OF DELETE AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM deleted WHERE SomeVal = 'Nonsense')
THROW 95302, N'Error Msg', 16; --Use an error number appropriate for you
ELSE
DELETE MT FROM dbo.MyTable MT JOIN deleted ON MT.id = deleted.id;
END;
GO

How to create trigger to auto-fill a column in my application as counter?

I have written a trigger, but it doesn't work well.
How to make it work to fill the column automatically, without user intervention, when I create an activity?
I use SQL Server.
You need an after trigger and not an instead of trigger change your trigger to after trigger
CREATE TRIGGER TriggerName
AFTER INSERT
ON TableName
BEGIN
//Your Code
END;

Get the operation type inside a "Insert or Update" trigger

Can we capture inside a Insert or Update trigger that this triggers has been executed because of Insert or due to an Update statement?
One way to know this is to make separate triggers for both Insert and Update
But it would be very nice if I can do this inside one trigger.
You can use Conditional Predicates INSERTING/UPDATING/DELETING inside the trigger to determine
which DML fired the trigger.
Sample trigger:
create trigger sample_trigger
before insert or update
on sample_table
for each row
begin
case
when inserting then
--do something
when updating then
--do something
end case;
end;

MSSQL Trigger - Issue

I have a SQL trigger on a table, which will fire after insert, update and delete.
I insert all the affected records in a separate physical table with codes defining the state of update. Following code snippet is the trigger defined.
CREATE TRIGGER [dbo].[DATA_CACHE]
ON [dbo].[DATA_USAGE]
for Insert,Update,Delete
AS
BEGIN
if(select COUNT(*) from inserted)>0
begin
if (select COUNT(*) from deleted)>0
BEGIN
--update
INSERT INTO CACHE_UPDATE_TABLE (CODE, ID, DATE, COUNT)
SELECT 2, ins.ID, ins.DATE, ins.COUNT
from inserted ins
END
else
begin
-- insert
INSERT INTO CACHE_UPDATE_TABLE (CODE, ID, DATE, COUNT)
SELECT 1, ins.ID, ins.DATE, ins.COUNT
from inserted ins
end
END
else
BEGIN
-- delete
INSERT INTO CACHE_UPDATE_TABLE (CODE, ID, DATE, COUNT)
SELECT 3, del.ID, del.DATE, del.COUNT
from deleted del
end
END
SELECT * FROM CACHE_UPDATE_TABLE
As you can see in the above trigger i had added an additional statement after the trigger by MISTAKE, selecting all values from the target table. This statement was after the defined trigger, however when i tried to alter the trigger, by right clicking on trigger and selecting modify, it also showed me the select statement after the end block of trigger.
Does this mean, every time the trigger is fired this select statement executes ? this is my first question (Question A) - May be a silly one, but i am a little confused about this.
My second question is (Question B) I encounter locking issue on the CACHE_UPDATE_TABLE, could this be the reason for locking? Also there is a SQL job which runs every one minute to check the CACHE_UPDATE_TABLE table, and then i perform some operation(linked server related) and delete these records from CACHE_UPDATE_TABLE after i am done. Locking Issue could be because of this?? and if so, how do i counter it?
My third question is (Question C) Is this the best way to do this operation using triggers or can i do it some other way? Is the trigger defined proper?
-Any help will be appreciated... Thanks.
You've got a lot of different questions in there which is probably why you've not received any answers, but I'll cover what I can.
A) That's quite an interesting question actually. I would have assumed that it would do nothing - It'd be executed when you create the trigger but then wouldn't be part of the trigger - however I've noticed odd behaviour with this before so I tested with a simple stored procedure:
CREATE PROCEDURE dbo.test ( #i INT ) AS
BEGIN
SELECT #i
END;
SELECT 'hi'
GO
Executing the stored procedure causes the SELECT 'hi' to fire as well as the SELECT #i. I still don't have an answer for your question, but I would definitely make sure not to have any stray SQL outside the trigger when you create it for this reason alone.
I've just investigated this a little more and apparently the end of the stored procedure is wherever the first GO is after the procedure (which SQL Server automatically adds to the end if you don't use one). So you could define your whole procedure after the END - you can still use the parameters too.
This seems to be because the BEGIN and END aren't a required part of the stored procedure definition - they're not actually indicating the begin and end of the stored procedure, they're just an unrelated BEGIN...END block like you might put after and IF statement. You can have as many BEGIN...END blocks as you like in the procedure definition, or none at all.
C) I would definitely change your trigger. You've massively complicated it by combining the 3 triggers without reusing any code. The only reason to combine INSERT,UPDATE and DELETE triggers is so that you don't have to duplicate code. You should either:
Have 3 separate triggers, each containing only the relevant INSERT - that way you remove all of the conditional logic.
Keep them together but work out only the CODE using some conditional logic and have only 1 INSERT statement.
I'd be tempted to go with the 3 separate triggers, or at least an separate out the delete trigger, and then use CASE del.ID IS NULL THEN 1 ELSE 2 END for the CODE on the INSERT/UPDATE trigger. But you could combine them with (untested):
INSERT INTO CACHE_UPDATE_TABLE (CODE, ID, DATE, COUNT)
SELECT CASE WHEN del.ID IS NULL THEN 1
WHEN ins.ID IS NULL THEN 3
ELSE 2 END
,ISNULL(ins.ID, del.ID)
,ISNULL(ins.DATE, del.DATE)
,ISNULL(ins.COUNT, del.COUNT)
FROM deleted del
FULL OUTER JOIN inserted ins ON del.ID = ins.ID
Just remove that
SELECT * FROM CACHE_UPDATE_TABLE

SQL Server: pause a trigger

I am working with SQL Server 2005 and I have trigger on a table that will copy an deletions into another table. I cannot remove this trigger completely. My problem is that we have now developed an archiving strategy for this table. I need a way of "pausing" a trigger when the stored proc that does the archiving runs.
A little more detail would be useful on how the procedure is accessing the data, but assuming you are just getting the data, then deleting it from the table and wish to disable the trigger for this process, you can do the following
DISABLE TRIGGER trg ON tbl;
then
ENABLE TRIGGER trg ON tbl;
for the duration of the procedure.
This only works for SQL 2005+
An alternative method is to use Context_Info to disable it for a single session, while allowing other sessions to continue to fire the trigger.
Context_Info is a variable which belongs to the session. Its value can be changed using SET Context_Info.
The trigger will mostly look like this:
USE AdventureWorks;
GO
-- creating the table in AdventureWorks database
IF OBJECT_ID('dbo.Table1') IS NOT NULL
DROP TABLE dbo.Table1
GO
CREATE TABLE dbo.Table1(ID INT)
GO
-- Creating a trigger
CREATE TRIGGER TR_Test ON dbo.Table1 FOR INSERT,UPDATE,DELETE
AS
DECLARE #Cinfo VARBINARY(128)
SELECT #Cinfo = Context_Info()
IF #Cinfo = 0x55555
RETURN
PRINT 'Trigger Executed'
-- Actual code goes here
-- For simplicity, I did not include any code
GO
If you want to prevent the trigger from being executed you can do the following:
SET Context_Info 0x55555
INSERT dbo.Table1 VALUES(100)
Before issuing the INSERT statement, the context info is set to a value. In the trigger, we are first checking if the value of context info is the same as the value declared. If yes, the trigger will simply return without executing its code, otherwise the trigger will fire.
source: http://www.mssqltips.com/tip.asp?tip=1591
if DISABLE TRIGGER/ENABLE TRIGGER is not an option for some reason, you can create a table with a single row which will serve as a flag for the trigger.

Resources