SQL Trigger - How do I test for the operation? - sql

My trigger fires on INSERT, UPDATE and DELETE. I need to insert from the appropriate in memory table (inserted, deleted) depending upon which operation triggered the trigger. Since only inserted is populated on INSERT or deleted on DELETE I figure I can just do an insert and if there's no rows and I'm good.
But, UPDATE populates both tables. I only want the values from deleted on UPDATE. I tried testing for update using UPDATE(column) function, but this returns TRUE even on INSERT. So, how can I test for UPDATE?
ALTER TRIGGER CREATE_tableAudit
ON dbo.table
FOR INSERT, UPDATE, DELETE
AS
BEGIN
IF(UPDATE([column1]))--returns true on INSERT :(
BEGIN
INSERT INTO [dbo].[tableAudit]
([column1]
,[CreateDate]
,[UpdateDate])
SELECT * from deleted --update
END
ELSE
BEGIN
--only inserted is populated on INSERT, visa-versa with DELETE
INSERT INTO [dbo].[tableAudit]
([column1]
,[CreateDate]
,[UpdateDate])
select * from inserted --insert
INSERT INTO [dbo].[tableAudit]
([column1]
,[CreateDate]
,[UpdateDate])
select * from deleted --delete
END

To test for UPDATE, look for identical primary key values in both the Inserted and Deleted tables.
/* These rows have been updated */
SELECT i.PKColumn
FROM inserted i
INNER JOIN deleted d
ON i.PKColumn = d.PKColumn

Assuming that the primary keys of rows didn't change, you can find updated rows by joining the Inserted and Deleted tables on the primary key field(s). If joining these two tables produces rows, then you can safely assume that those rows were updated.
If an update does change the primary key of a row, then you're probably better off just treating it as two operations, a delete and an insert.

The following has been useful to in triggers:
The * in the queries could be changed to include only fields you want to have compared; could exclude the autonumber if it changes in the source table.
To check for Inserted:
if exists (Select * from inserted) and not exists(Select * from deleted)
begin
...
end
To check for Updated:
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
...
end
To check for Deleted:
if exists(select * from deleted) and not exists(Select * from inserted)
begin
...
end

Related

SQL Server trigger validation to insert or update

I have to develop a trigger for multiple value update for the Change_Table that contains two columns Article_C (primary key) and Status_C. The trigger activates when the Status_C column is updated and it needs to either insert or update the Target_Tablewhich columns are Article_T (primary key) and Status_T.
The Status column for both tables is a NOT NULL int
For insert validation: insert all Change_Table values (Articles & Status) that do not exist into the Target_Table.
For update condition: if the articles exist in the Target_Table, pass the updated status value to that table.
Status values are 1 or 2.
My current implementation:
CREATE TRIGGER [dbo].[Article_Trigger]
ON [dbo].[Change_Table]
AFTER UPDATE
NOT FOR REPLICATION
AS
IF UPDATE (Status_C)
BEGIN
INSERT INTO Target_Table (Article_T, Status_T)
SELECT Article_C, Status_C
FROM Change_Table
WHERE NOT EXISTS (SELECT * FROM Target_Table
WHERE Change_Table.Article_C = Target_Table.Article_T
AND Change_Table.Status_C = Target_Table.Status_T)
END
This is a rough idea of the insert but it only works once when the Change_Table is first updated and the target table is empty. After that I get an error "Violation of PRIMARY KEY constraint" due to duplicate primary key after updating the status for a second time due to the insert condition.
Query that gave error after second execution:
update Change_Table set status_c = 1 where Article_C in (1000,1003)
How can I modify this query to implement the update status condition to this trigger?
I think you could use deleted or inserted tables. These 2 virtual tables are working nicely with trigger. In you example, you may not need deleted table as you are not logging the historical changes.
CREATE TRIGGER [dbo].[Article_Trigger]
ON [dbo].[Change_Table]
AFTER UPDATE
NOT FOR REPLICATION
AS
IF UPDATE (Status_C)
BEGIN
--insert if not exist
INSERT INTO Target_Table
SELECT A.Article_C, A.Status_C
FROM inserted as A --the updated records from the source table will exist in the inserted virtual table
LEFT JOIN Target_Table as B
ON B.Article_T = A.Article_C
WHERE B.Article_T IS NULL
--update if exist
UPDATE A
SET A.Status_T = B.Article_C
FROM Target_Table as A
INNER JOIN inserted as B --the updated records from the source table will exist in the inserted virtual table
ON B.Article_C = A.Article_T
END

Prevent duplicate data in using After Insert Trigger

I can detect duplicate records, but when I'm inserting new data it will detect it as a duplicate record even if doesn't already exist.
Here is my code:
ALTER TRIGGER [dbo].[SDPRawInventory_Dup_Trigger]
ON [dbo].[SDPRawInventory]
AFTER INSERT
AS
DECLARE #Year float,
#Month float,
#SDPGroup nvarchar(255);
SELECT
#Year = i.InvYear, #Month = i.InvMonth, #SDPGroup = i.SDPGroup
FROM inserted i;
IF (SELECT COUNT(*) FROM SDPRawInventory A
WHERE A.InvYear = #Year
AND A.InvMonth = #Month
AND A.SDPGroup = #SDPGroup) >= 1
BEGIN
RAISERROR ('Duplicate data', 16, 1)
ROLLBACK;
END
ELSE
BEGIN
INSERT INTO SDPRawInventory
SELECT * FROM inserted;
END
This is the table
And to clarify there is no primary key nor unique identifier.
If you are unable to put a constraint in place, then you need to handle the fact that Inserted may have multiple records. And because its an after insert trigger, you don't need to do anything if no duplicates are found because the records are already inserted.
ALTER TRIGGER [dbo].[SDPRawInventory_Dup_Trigger]
ON [dbo].[SDPRawInventory]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (
SELECT 1
FROM dbo.SDPRawInventory S
INNER JOIN Inserted I ON
-- Test for a duplicate
S.InvYear = I.InvYear
AND S.InvMonth = I.InvMonth
AND S.SDPGroup = I.SDPGroup
-- But ensure the duplicate is a *different* record - assumes a unique ID
AND S.ID <> I.ID
)
BEGIN
THROW 51000, 'Duplicate data.', 1;
END;
END;
Note the simplified and modern error handling.
EDIT: And if you have no unique key, and no permission to add one, then you need an instead of trigger to only insert non-duplicates e.g.
ALTER TRIGGER [dbo].[SDPRawInventory_Dup_Trigger]
ON [dbo].[SDPRawInventory]
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
-- Reject the entire insert if a single duplicate exists
-- Note if multiple records are inserted, some of which are duplicates and some of which aren't, they all get rejected
IF EXISTS (
SELECT 1
FROM dbo.SDPRawInventory S
INNER JOIN Inserted I ON
-- Test for a duplicate
A.InvYear = I.InvYear
AND A.InvMonth = I.InvMonth
AND A.SDPGroup = I.#SDPGroup
)
-- Test that Inserted itself doesn't contain duplicates
OR EXISTS (SELECT 1 FROM Inserted GROUP BY InvYear, InvMonth, SDPGroup HAVING COUNT(*) > 1)
BEGIN
THROW 51000, 'Duplicate data.', 1;
END;
INSERT INTO dbo.SDPRawInventory (SDP_SKU_DESC, WholeQty, InvYear, InvMonth, SDPGroup, invUOM, LooseQty)
SELECT SDP_SKU_DESC, WholeQty, InvYear, InvMonth, SDPGroup, invUOM, LooseQty
FROM Inserted I
WHERE NOT EXISTS (
SELECT 1
FROM dbo.SDPRawInventory S
-- Test for a duplicate
WHERE S.InvYear = I.InvYear
AND S.InvMonth = I.InvMonth
AND S.SDPGroup = I.SDPGroup
);
END;
Note: This doesn't do anything to handle existing duplicates.
This trigger is executed after the new records were inserted, so it will at least find the original records in the SELECT COUNT statement. Changing >= 1 into >= 2 can only partially fix this when inserting is guaranteed to occur one record as a time. Moreover, it will still fail when there were already multiple duplicated of the newly inserted record in the database before the insert.
You need to exclude the latest inserted records from the COUNT. But a better idea would probably be to add a UNIQUE constraint for preventing duplicates, so no trigger would be necessary.
If adding a constraint is not possible yet, you should initiate a clean-up process to eliminate the existing duplicates beforehand. Everything else is looks pretty flawed to me, since it is unlikely the current approach will ever bring the table into a state with no duplicates.
You are creating the infinite loop. You just have to remove the insertion part from your trigger.
ELSE
BEGIN
INSERT INTO SDPRawInventory
SELECT * FROM inserted;
END
This should not be in the trigger as trigger is called as part of insertion. you should not write actual insertion in to table in trigger.

After insert not working

all id columns has auto_increment
In my trigger:
ALTER trigger [dbo].[mytrig]
on [dbo].[requests]
after INSERT, UPDATE
as
begin
declare #MyId1 int
set #MyId1 = (select Id from inserted)
declare #MyId2 int
declare #MyId3 int
if (select column1 from inserted) = 1
begin
insert into [dbo].[contracts] select column1,column2,column3 .... from inserted
set #MyId2 = SCOPE_IDENTITY()
insert into [dbo].[History] select column1,column2,column3 .... from inserted
set #MyId3 = SCOPE_IDENTITY()
insert into [dbo].[contracts_depts](Id_Contract ,column5) select #MyId2,column6 from request_depts where Id_request=#MyId1
insert into [dbo].[History_depts] (Id_InHistory,column5) select #MyId3,column6 from request_depts where Id_request=#MyId1
end
end
#MyId1 returns value only after update but not after insert. Do I have to use scope_identity() or something ?
Your main issue is: you're assuming the triggers is called once per row - that is NOT the case!
The trigger is called once per statement, and if your statement affects multiple rows, the Inserted pseudo table will contain multiple rows - so your statement here
set #MyId1 = (select Id from inserted)
really isn't going to work - it will select one arbitrary row (out of however many there are).
You'll need to rewrite your trigger to take this fact into account! Assume that Inserted contains 100 rows - how do you want to deal with that? What are you trying to achieve? Triggers don't return values - they will record into an audit table, or update other rows, or something like that ....

Deleted Virtual table in SQL Server is empty ON Delete trigger

I am trying to invoke an ON Delete trigger event, but when I try to select row from the Deleted table, it is empty.
Is there any other way to get Id of row on which delete event has fired?
Code:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER TRIGGER [audit]
ON [dbo].[S_PARTY]
FOR DELETE
AS
-- Insert statements for trigger here
DECLARE #id nvarchar(50)
SET #id = (Select ROW_ID from deleted )
BEGIN
-- Insert statements for trigger here
INSERT INTO [dbo].[S_AMF_AUDIT_ITEM] (ROW_ID)
VALUES (#id);
END
When trigger fires on this, I am getting error as S_AMF_AUDIT_ITEM doesn't allow null values. So can you please help me this to get Id of table on which delete command executes?
Your trigger is broken.
It doesn't take into account that the DELETE statement might affect zero or more than one rows.
The issue with NULL could occur for the statement DELETE FROM [dbo].[S_PARTY] WHERE 1 = 0.
A fixed version would be
ALTER TRIGGER [audit]
ON [dbo].[S_PARTY]
FOR DELETE
AS
BEGIN
INSERT INTO [dbo].[S_AMF_AUDIT_ITEM]
(ROW_ID)
SELECT ROW_ID
FROM deleted;
END
A trigger can fire for 0..N deleted rows. For example:
delete YourTable
where 1=2
Would run a for delete trigger on YourTable. So a trigger has to be able to deal with zero or multiple rows. Consider rewriting your trigger like:
ALTER TRIGGER [audit] ON [dbo].[S_PARTY] FOR DELETE
AS
INSERT dbo.S_AMF_AUDIT_ITEM
(ROW_ID)
SELECT ROW_ID
FROM deleted
That will work for any number of inserted rows.

How to create a trigger that uses INSERT , DELETE , UPDATE events

I want to create a trigger for logging.So i need event names of INSERT,UPDATE or DELETE.i.e : one of these statements is used in query execution my trigger will trig and starts logging.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER LogBuses
ON Bus_table
AFTER INSERT,DELETE
AS
BEGIN
DECLARE #PlateNo nvarchar(50)
IF INSERT//something like that-INSERTING- DELETING
SELECT #PlateNo=PlateNo from inserted
insert into Logger (EffectedTable,ActionName,EffectDate,EffectedID)
VALUES ('Bus_table','Insert',SYSDATETIME (),#PlateNo);
ELSE IF DELETE
SELECT #PlateNo=PlateNo from deleted
insert into Logger (EffectedTable,ActionName,EffectDate,EffectedID) VALUES ('Bus_table','Insert',SYSDATETIME (),#PlateNo);
END
GO
You use the inserted and deleted tables. It's inserted if just the inserted table is populated, deleted if just the deleted table is populated, and updated if both tables are populated. Use if exists (select 1 from inserted) to test.
if exists (select 1 from inserted) and exists (select 1 from deleted)
--update
else if exists (select 1 from inserted)
--insert
else if exists (select 1 from deleted)
--delete
Create a stored procedure that logs, and triggers for each event, that call the procedure, passing the needed data.