Is this possible to create one trigger for Insert and Update operations in SQLite?
I mean, something like this:
CREATE TRIGGER dbo.TR_TableName_TriggerName
ON dbo.TableName
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS(SELECT * FROM INSERTED)
-- DELETE
PRINT 'DELETE';
ELSE
BEGIN
IF NOT EXISTS(SELECT * FROM DELETED)
-- INSERT
PRINT 'INSERT';
ELSE
-- UPDATE
PRINT 'UPDATE';
END
END;
It's for MS SQL i think, source: Insert Update trigger how to determine if insert or update
Edit:
Is it possible to create also one trigger for more than one table?
No, the syntax graph for CREATE TRIGGER clearly shows that only one of INSERT, UPDATE or DELETE can be given.
It also shows that only one table can be given as a table to trigger on.
Related
I've created and worked with Triggers in Oracle for years however I'm unable to wrap my head around how to update a field when inserting data into a sqlite database.
All I want to do is create a trigger that automatically inserts the current DateTime into a column in the sqlite database named 'createdDate' for ANY record that is inserted.
What is the best approach to accomplish this?
Below is what I've attempted without success.
CREATE TRIGGER outputLogDB_Created_Trig
BEFORE INSERT
ON outputLog
WHEN NEW.createdDate IS NULL
BEGIN
SELECT CASE WHEN NEW.createdDate IS NULL THEN NEW.createdDate = datetime('now', 'localtime') END;
END;
The above is almost a replica of how I would implement my triggers in Oracle with some modifications of course for sqlite. The logic is basically identical.
What am I missing?
Later Edit - I can get it to work if I instead use AFTER INSERT and not using FOR EACH ROW
CREATE TRIGGER outputLog_Created_Trig
AFTER INSERT
ON outputLog
WHEN New.createdDate IS NULL
BEGIN
UPDATE outputLog
SET createdDate = datetime('now', 'localtime')
WHERE outputLog_ID = New.rowid;
END;
But why can't I just insert the record using the new value while I'm inserting it? Am I ONLY able to get this in there using an Update AFTER I've already inserted the record?
The issue I have with this is the fact that I'd like to have a NOT NULL constraint on the createdDate column. Perhaps I'm simply used to how I've done it for years in Oracle? I realize the Trigger 'should' take care of any record and force this field to NEVER be NULL. It's just that NOT being able to add the constraint for some reason makes me uneasy. Do I need to let go of this worry?
Thanks to Shawn pointing me toward an easy simple solution to my problem. All that is needed in a SQLite database to insert the current Date/Time for each record being inserted is to set the DEFAULT value on that column to CURRENT_TIMESTAMP.
Since I wanted the timestamp in my own local time see below my create table script that is the solution to my problem.
CREATE TABLE outputLog (
outputLog_ID INTEGER PRIMARY KEY ASC ON CONFLICT ROLLBACK AUTOINCREMENT
NOT NULL ON CONFLICT ROLLBACK,
outputLog TEXT,
created DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime') )
NOT NULL )
;
Here is my simple PL/SQL code for demonstration purpose.
create table cust(cname varchar(10));
set SERVEROUTPUT ON;
create or replace trigger tgr
before insert on cust
for each row
enable
begin
dbms_output.put_line('Trigger hit on insert');
end;
/
insert into cust values('John');
OUTPUT:/
Table CUST created
Trigger TGR compiled
1 row inserted // *EXPECTING* Trigger hit on insert
You can't use DBMS_OUTPUT.PUT_LINE because when you insert data to your table, there is no prompt or screen which shows the execution of trigger. this applied same for procedures , functions , triggers.
Don't use commit inside a table. it will throw an exception. if you want to use commit then make the trigger pragma autonomous_transaction (i suggest not to use commit.it will automatically commit) .
Also make sure you don't modify the same table in the trigger. it will also throw and exception for mutating the data.
sample code
create table cust(cname varchar(10));
create table log(log varchar(10));
create or replace trigger tgr
before insert on cust
for each row
enable
begin
insert into log values('test');
end;
/
Don't use DBMS_OUTPUT.PUT_LINE inside a trigger to check if it was fired or not. Some of the IDEs like SQL developer might not output the message , even if you use SET SERVEROUTPUT ON.
However it could work on sqlplus . When i tried, it did display the message in sqlplus. So, it is not an issue with the database or your trigger.
SQL> insert into cust values('John');
Trigger hit on insert
And if you issue commit or rollback on the transaction, the messages might appear in sql developer.
I would suggest , it is better if you can create a log table and try to insert records into it rather than use dbms_output.
begin
INSERT INTO LOG_TABLE ( log_date,log_message) VALUES (SYSDATE,'Trigger hit on insert');
end;
/
The questions says it all really.
I have a table and I want to insert a row if it doesn't already exist.
or should I just do an insert and if the key constraint is violated then ignore it?
Use INSERT OR IGNORE: http://www.sqlite.org/lang_insert.html
Use a trigger that fires before INSERTs and discards the duplicate row, something along the lines of...
CREATE TRIGGER trigger_name
BEFORE INSERT on your_table
FOR EACH ROW WHEN EXISTS (SELECT * FROM your_table WHERE id = NEW.id)
BEGIN
SELECT RAISE(IGNORE);
END;
i am trying to insert some rows and update some rows inside a pl/sql loop.
however all i get to see is the pl/sql procedure is successfully completed.
i do get to see dbmbs_ouput statements but not the output status of insert and/or update queries.
the serveroutput is set to on.
how do i get to see the status of insert and update rows(namely how many rows were inserted and updated)
In Oracle, the rowcount is not output automatically like it is in SQL Server.
You should do it explicitly:
BEGIN
INSERT
INTO mytable
SELECT …
FROM other_table;
DBMS_OUTPUT.put_line(SQL%ROWCOUNT);
END;
I'm working on setting up a simple SQLite database to access via Python. So far I have one basic table, and a couple of triggers - I want to have one trigger update a field column 'date_added' when a new record is added, and another one to update a column 'date_updated' when a record is later updated. Here is my SQLite syntax for the triggers:
CREATE TRIGGER add_contact AFTER INSERT ON contact_info
BEGIN
UPDATE contact_info SET date_added = DATETIME('NOW') WHERE pkid = new.pkid;
END;
CREATE TRIGGER update_contact AFTER UPDATE ON contact_info
BEGIN
UPDATE contact_info SET date_updated = DATETIME('NOW') WHERE pkid = new.pkid;
END;
The 'add_contact' trigger seems to be working fine... it fires when I add a new record via an sql INSERT command, as planned.
The problem seems to be the 'update_contact' trigger... it fires both when I update a record via an sql UPDATE command (as planned) and when I add a new record also:
i.e. when I add a new record I get this in the 'date_added' and 'date_updated' columns:
2010-07-12 05:00:06|2010-07-12 05:00:06
and when I update that record, it changes like so:
2010-07-12 05:00:06|2010-07-12 05:14:26
I guess I'm not getting why the UPDATE trigger fires on INSERT also?
TIA,
Monte
Edited to add: Any hints on how to make it work as intended?
A better way to avoid the original problem is to use a DEFAULT ( DATETIME('NOW') )
clause for the date_added column in the table definition, instead of using an INSERT trigger.
You have an UPDATE in your INSERT trigger. So the INSERT causes an UPDATE. Which you have hooked with a different trigger.