I need to delete an existing row when a new row is inserted.
For example, there is an existing row where its status is ready and ID is 2478.
When a new row is inserted, let's say status is completed and ID is 2478, the trigger would find matching ID 2478 and delete the row since status is completed.
At the same time, I also need to delete the inserted row as well (one with status completed)
Can this be done with trigger? ex: AFTER INSERT
Yes, this can be done in a trigger. The example below deletes all rows for a given ID whenever a row with status completed is inserted for that ID.
CREATE TABLE dbo.YourTable(
ID int
,Status varchar(10)
CONSTRAINT PK_YourTable PRIMARY KEY(ID, Status)
);
GO
CREATE TRIGGER TR_YourTable ON dbo.YourTable
FOR INSERT
AS
SET NOCOUNT ON;
DELETE target
FROM dbo.YourTable AS target
JOIN inserted ON inserted.ID = target.ID
WHERE inserted.Status = 'completed';
GO
INSERT INTO dbo.YourTable VALUES(2478,'pending');
SELECT * FROM dbo.YourTable;
INSERT INTO dbo.YourTable VALUES(2478,'ready');
SELECT * FROM dbo.YourTable;
INSERT INTO dbo.YourTable VALUES(2478,'completed');
SELECT * FROM dbo.YourTable;
GO
Related
After searching many pages I still can't find the answer about re-inserting deleted rows in the same table - not another table.
I have a table named timetable with the primary key made up from 3 columns Schoolcode, Year, Term.
I need for some reason need to insert deleted rows into the same table.
I get the error
Violation of PRIMARY KEY constraint
with the following trigger
ALTER TRIGGER [dbo].[AFTER_delete_]
ON [dbo].timetable
AFTER delete
AS
BEGIN
IF EXISTS (SELECT * FROM deleted)
BEGIN
INSERT INTO timetable
SELECT *
FROM deleted A
WHERE NOT EXISTS (SELECT 1 FROM timetable B
WHERE B.Schoolcode = A.Schoolcode
AND B.Year = A.Year
AND B.Term = A.Term);
END
END
thanks any way.I test the code below and that did work.
ALTER TRIGGER [dbo].[Instead_OfDelSert_Status]
ON [dbo].[Status]
INSTEAD OF delete,insert
AS
BEGIN
PRINT 'You must disable or delete Trigger Instead_OfDelSert_Status to insert or
delete rows!'
END
I don't write T-SQL code too often so how do I capture updated row in a trigger?
If I create a trigger for INSERT I can ask for records from inserted as in
Create Trigger [dbo].[tr_test]
on table1
for INSERT
as
declare #id int
select #id = i.RecordId from inserted as I
...
How do I do that for UPDATE?
There are are two trigger or magic tables in sql server that is inserted or deleted table.
If you are creating trigger for Insert
- data comes in only inserted table in deleted table there is no records find
Create Trigger [dbo].[tr_test]
on table1
for INSERT
as
if exists (select 1 from inserted) and not exists(select 1 from deleted)
-- Action which would you want For Insert
If you are creating trigger for Update
- updated data comes in only inserted table and previous data comes in deleted table there is no records find
Create Trigger [dbo].[tr_test]
on table1
for UPDATE
as
if exists (select 1 from inserted) and exists(select 1 from deleted)
-- Action which would you want when your target table has been update
If you are creating trigger for Delete
- Deleted data comes in Deleted table and in case of deleting data it not comes inserted table.
Create Trigger [dbo].[tr_test]
on table1
after Delete
as
if exists (select 1 from deleted ) and not exists(select 1 from inserted)
-- Action which would you want when your target table has been delete
The same way as with an insert trigger. In an update trigger, inserted contains the new values, and deleted contains the old.
Quoth the docs:
The deleted table stores copies of the affected rows during DELETE and UPDATE statements. During the execution of a DELETE or UPDATE statement, rows are deleted from the trigger table and transferred to the deleted table. The deleted table and the trigger table ordinarily have no rows in common.
The inserted table stores copies of the affected rows during INSERT and UPDATE statements. During an insert or update transaction, new rows are added to both the inserted table and the trigger table. The rows in the inserted table are copies of the new rows in the trigger table.
An update transaction is similar to a delete operation followed by an insert operation; the old rows are copied to the deleted table first, and then the new rows are copied to the trigger table and to the inserted table.
Source: DML Triggers, Use the inserted and deleted Tables
I want to create a before delete trigger. When I delete a record from a table that record has to be inserted into a history table. How can I do this in SQL Server?
In this situation, you're probably better off doing a regular "after" trigger. This is the most common approach to this type of situation.
Something like
CREATE TRIGGER TRG_AUD_DEL
ON yourTable
FOR DELETE
AS
INSERT INTO my_audit_table (col1, col2, ...)
SELECT col1, col2...
FROM DELETED
What will happen is, when a record (or records!) are deleted from your table, the deleted row will be inserted into my_audit_table The DELETED table is a virtual table that contains the record(s) as they were immediately prior to the delete.
Also, note that the trigger runs as part of the implicit transaction on the delete statement, so if your delete fails and rolls back, the trigger will also rollback.
You could also use INSTEAD OF DELETE
CREATE TRIGGER dbo.SomeTableYouWhatToDeleteFrom
ON dbo.YourTable
INSTEAD OF DELETE
AS
BEGIN
-- Some code you want to do before delete
DELETE YourTable
FROM DELETED D
INNER JOIN dbo.YourTable T ON T.PK_1 = D.PK_1
END
It could be done in following steps for let’s say in this example I am using customer table:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
LAST_UPDATED DATETIME,
PRIMARY KEY (ID)
);
Create History:
CREATE TABLE CUSTOMERS_HIST(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
LAST_UPDATED DATETIME,
PRIMARY KEY (ID)
);
Trigger on source table like below on delete event:
CREATE TRIGGER TRG_CUSTOMERS_DEL
ON CUSTOMERS
FOR DELETE
AS
INSERT INTO CUSTOMERS_HIST (ID, NAME, AGE, ADDRESS, LAST_UPDATED)
SELECT ID, NAME, AGE, ADDRESS, LAST_UPDATED
FROM DELETED
Try a trigger that executes before the delete and throws an error when the condition is not met.
CREATE TRIGGER [dbo].[TableName_PreventDeleteAndUpdate]
ON dbo.TableName
FOR DELETE, UPDATE -- runs before deletes and updates
AS
BEGIN
IF (APP_NAME() <> 'SomeApp')
BEGIN
RAISERROR ('Only delete/update with SomeApp', 16, 1);
ROLLBACK TRANSACTION;
RETURN;
END
END
I have a simple details table like so:
listid
custid
status
last_changed
The primary key consists of both listid and custid.
Now I'm trying to setup a trigger that sets the last_changed column to the current datetime every time an insert or update happens. I've found lots of info on how to do that with a single PK column, but with multiple PKs it gets confusing on how to correctly specify the PKs from the INSERTED table.
The trigger has to work in SQL Server 2005/2008/R2.
Thanks for a working trigger code!
Bonus would be to also check if the data was actually altered and only update last_changed in that case but for the sake of actually understanding how to correctly code the main question I'd like to see this as a separate code block if at all.
Hmm.... just because the primary key is made up of two columns shouldn't really make a big difference....
CREATE TRIGGER dbo.trgAfterUpdate ON dbo.YourTable
AFTER INSERT, UPDATE
AS
UPDATE dbo.YourTable
SET last_changed = GETDATE()
FROM Inserted i
WHERE dbo.YourTable.listid = i.listid AND dbo.YourTable.custid = i.custid
You just need to establish the JOIN between the two tables (your own data table and the Inserted pseudo table) on both columns...
Are am I missing something?? .....
CREATE TRIGGER dbo.trgAfterUpdate ON dbo.YourTable
AFTER INSERT, UPDATE
AS
UPDATE dbo.YourTable
SET last_changed = GETDATE()
FROM Inserted i
JOIN dbo.YourTable.listid = i.listid AND dbo.YourTable.custid = i.custid
WHERE NOT EXISTS
(SELECT 1 FROM Deleted D Where D.listid=I.listid AND D.custid=i.custid AND (D.status=i.status)
Here i assuming that stasus column is not nullable. If yes, you should add additional code to check if one of columns is NULL
You can check every field in trigger by comparing data from inserted and deleted table like below :
CREATE TRIGGER [dbo].[tr_test] ON [dbo].[table]
AFTER INSERT, UPDATE
AS
BEGIN
DECLARE #old_listid INT
DECLARE #old_custid INT
DECLARE #old_status INT
DECLARE #new_listid INT
DECLARE #new_custid INT
DECLARE #new_status INT
SELECT #old_listid=[listid], #old_custid=[custid], #old_status = [status] FROM [deleted]
SELECT #new_listid=[listid], #new_custid=[custid], #new_status = [status] FROM [inserted]
IF #oldstatus <> #new_status
BEGIN
UPDATE TABLE table SET last_changed = GETDATE() WHERE [listid] = #new_listid AND [custid] = #new_custid
END
END
I want to insert rows into the audit table whenever an insert, update or delete takes place in the master table "Table1" - doesn't matter which column is changed/inserted. I also want to add I, U or D on insert, update or delete. For insert and delete I am checking if rows exist in the inserted and deleted table. What is the best way to approach update.
My code for insert and delete is :
CREATE TRIGGER [dbo].[tr_Table1_InsertUpdate_Table1History_Insert]
ON [dbo].[Table1]
FOR INSERT, DELETE, UPDATE
AS
BEGIN
IF EXISTS(SELECT * FROM Inserted)
BEGIN
INSERT INTO Table1History(...., ModificationType)
SELECT ..., 'I'
FROM Inserted
END
IF EXISTS(SELECT * FROM Deleted)
BEGIN
INSERT INTO Table1History(..., ModificationType)
SELECT ..., 'D'
FROM Deleted
END
END
GO
Kindly help!
For updates, the original values for the row will be added to the deleted table, and the new values for the row will be added to the inserted table. So, to identify inserts, deletes and updates you would do the following
Inserts - get the rows from inserted that are not in deleted
Deletes - get the rows from deleted that are not in inserted.
Updates - get the rows that are in both inserted and deleted
Below is an example of a trigger generated by ApexSQL Audit
It’s not a cheap tool but you can probably use it in trial mode to get the job done.
Notice the INSERT INTO dbo.AUDIT_LOG_DATA part and repeat it for every column you want to audit.
There are two tables in the background for storing the data and several stored procedures as well but this will get you going in the right direction.
CREATE TRIGGER [dbo].[tr_d_AUDIT_TableName]
ON [dbo].[TableName]
FOR DELETE
NOT FOR REPLICATION
AS
BEGIN
DECLARE
#IDENTITY_SAVE varchar(50),
#AUDIT_LOG_TRANSACTION_ID Int,
#PRIM_KEY nvarchar(4000),
--#TABLE_NAME nvarchar(4000),
#ROWS_COUNT int
SET NOCOUNT ON
Select #ROWS_COUNT=count(*) from deleted
Set #IDENTITY_SAVE = CAST(IsNull(##IDENTITY,1) AS varchar(50))
INSERT
INTO dbo.AUDIT_LOG_TRANSACTIONS
(
TABLE_NAME,
TABLE_SCHEMA,
AUDIT_ACTION_ID,
HOST_NAME,
APP_NAME,
MODIFIED_BY,
MODIFIED_DATE,
AFFECTED_ROWS,
[DATABASE]
)
values(
'TableName',
'dbo',
3, -- ACTION ID For DELETE
CASE
WHEN LEN(HOST_NAME()) < 1 THEN ' '
ELSE HOST_NAME()
END,
CASE
WHEN LEN(APP_NAME()) < 1 THEN ' '
ELSE APP_NAME()
END,
SUSER_SNAME(),
GETDATE(),
#ROWS_COUNT,
'DatabaseName'
)
Set #AUDIT_LOG_TRANSACTION_ID = SCOPE_IDENTITY()
INSERT
INTO dbo.AUDIT_LOG_DATA
(
AUDIT_LOG_TRANSACTION_ID,
PRIMARY_KEY_DATA,
COL_NAME,
OLD_VALUE_LONG,
DATA_TYPE
, KEY1
)
SELECT
#AUDIT_LOG_TRANSACTION_ID,
convert(nvarchar(1500), IsNull('[Order_ID]='+CONVERT(nvarchar(4000), OLD.[Order_ID], 0), '[Order_ID] Is Null')),
'Order_ID',
CONVERT(nvarchar(4000), OLD.[Order_ID], 0),
'A'
, CONVERT(nvarchar(500), CONVERT(nvarchar(4000), OLD.[Order_ID], 0))
FROM deleted OLD
WHERE
OLD.[Order_ID] Is Not Null
END
Have you consider using AutoAudit?
AutoAudit is a SQL Server (2005, 2008)
Code-Gen utility that creates Audit
Trail Triggers with:
Created, CreatedBy, Modified, ModifiedBy, and RowVersion
(incrementing INT) columns to table
Insert event logged to Audit table
Updates old and new values logged to Audit table
Delete logs all final values to the Audit tbale
view to reconstruct deleted rows
UDF to reconstruct Row History
Schema Audit Trigger to track schema changes
Re-code-gens triggers when Alter Table changes the table