Creating a conditional SQL trigger in SQLite - sql

I’m trying to write a trigger for sqlite and just running into all kinds of problems. In truth I think my real problem is with my poor background in the sql language. Anyway here goes…
I have two tables Table1 and Table2. Table1 has a column named time (which is a 64bit integer time). I need a trigger that watches for a new row being inserted in Table1. If there are 3 or more rows in Table1 that have time greater than X (a hard coded value in the below example 120 seconds) I need to insert a new row into Table2.
Here is what I have so far (note this does not work)
CREATE TRIGGER testtrigger AFTER
INSERT ON Table1 WHEN
(
SELECT COUNT() AS tCount FROM
(
SELECT * FROM Table1 WHERE
time > (NEW.time - 120)
) WHERE tCount > 3
)
BEGIN
INSERT INTO Table2 (time, data) VALUES
(NEW.time, 'data1');
END
Any kind souls out there who are better in SQL than I?

This works because the WHEN clause needs an expression:
sqlite> .schema Table1
CREATE TABLE Table1 (time int);
CREATE TRIGGER testtrigger AFTER INSERT ON Table1
WHEN 3<(SELECT Count() FROM Table1 WHERE time>(NEW.time-120))
BEGIN
INSERT INTO Table2 (time, data) VALUES (NEW.time,'data1');
END;
Have you looked at this reference page? From what I can tell this is a "misuse of aggregate" which probably stems from statement in the When section. You had this:
sqlite> .tables
Table1 Table2
sqlite> .schema Table1
CREATE TABLE Table1 (time int);
CREATE TRIGGER testtrigger AFTER
INSERT ON Table1 WHEN
(
SELECT COUNT() AS tCount FROM
(
SELECT * FROM Table1 WHERE
time > (NEW.time - 120)
) WHERE tCount > 3
)
BEGIN
INSERT INTO Table2 (time, data) VALUES
(NEW.time, 'data1');
END;
sqlite> .schema Table2
CREATE TABLE Table2 (time int,data string);
sqlite> insert into Table1 VALUES (5);
SQL error: misuse of aggregate:
sqlite>
I tried deleting "WHERE tCount" to make it into an expression, but then I got a syntax error at the operator.
So instead I switched things about for the solution above.

Your WHEN clause in the trigger should be a comparison expression which returns true or false, instead of returning a number. Try dlamblin's idea.

Maybe a different syntactical approach?
CREATE TRIGGER testtrigger ON Table1
FOR INSERT
AS
BEGIN
DECLARE #timeNum int
SET #timeNum = SELECT count(*) FROM Table1 WHERE time > (New.time - 120)
IF #timeNum > 3
BEGIN
INSERT INTO Table2 (time, data) VALUES
(NEW.time, 'data1');
END
END
But also, try some debugging statements. When I was debugging my last trigger for a webservice I put some INSERT statements into a debugging table that I setup. So then you could output the #timeNum every time the trigger gets called, and then put another debug INSERT inside the loop to make see if you actually get into your Table2 INSERT logic.
UPDATE:
Sorry! Looks like SqlLite kinda sucks, I did not know that it lacked some of this syntax. Nonetheless, if you are not getting any answers, consider some debugging statements to make sure that your code paths are being called under the right conditions.

Related

ORACLE TRIGGER INSERT INTO ... (SELECT * ...)

Trigger with Insert into (select * ...)
I'm trying it.
INSERT INTO T_ USERS SELECT * FROM USERS WHERE ID = :new.ID;
not working...
this work.
INSERT INTO T_USERS(ID) VALUES(:new.ID);
Trigger
create or replace trigger "TRI_USER"
AFTER
insert on "USER"
for each row
begin
INSERT INTO T_USER SELECT * FROM USER WHERE ID = :new.ID;
end;​
this work.
INSERT INTO T_USERS(ID) VALUES(:new.ID);
So if it fits to you then try this:
INSERT INTO T_USER(ID) SELECT ID FROM USER WHERE ID = :new.ID;
If you want to select one or more rows from another table, you have to use this syntax:
insert into <table>(<col1>,<col2>,...,<coln>)
select <col1>,<col2>,...,<coln>
from ...;
Perhaps you could post the actual error you are experiencing?
Also, I suggest that you rethink your approach. Triggers that contain DML introduce all sorts of issues. Keep in mind that Oracle Database may need to restart a trigger, and could therefore execute your DML multiple times for a particular row.
Instead, put all your related DML statements together in a PL/SQL procedure and invoke that.
Its not about your trigger but because of INSERT statement
here insert statement works as below
INSERT INTO <TABLE>(COL1,COL2,COL3) VALUES (VAL1,VAL2,VAL3); --> If trying to populate value 1 by one.
INSERT INTO <TABLE>(COL1,COL2,COL3) --> If trying to insert mult vales at a time
SELECT VAL1,VAL2,VAL3 FROM <TABLE2>;
The number of values should match with number of columsn mentioned.
Hope this helps you to understand

UPDATE and INSERT should fire trigger only once

Is there any way to combine an update and an insert statements in a way that they fires a trigger only once?
I have one particular table that has (and currently needs) a trigger AFTER INSERT, UPDATE, DELETE. Now I want to update one row and insert another row and have the trigger fire only once for that.
Is this at all possible?
I already tried a MERGE-Statement without success: The trigger fires once for the update- and once for the insert-part.
Well, problem solved for me. I did NOT find a way to combine the statements into one fire-event of the trigger. But the trigger behaves in an interesting way, that was good enough for me: Both calls to the trigger do already have access to the fully updated data.
Just execute the following statements and you will see what I mean.
CREATE TABLE Foo (V INT)
GO
CREATE TRIGGER tFoo ON Foo AFTER INSERT, UPDATE, DELETE
AS
SELECT 'inserted' AS Type, * FROM inserted
UNION ALL
SELECT 'deleted', * FROM deleted
UNION ALL
SELECT 'actual', * FROM Foo
GO
DELETE FROM Foo
INSERT Foo VALUES (1)
;MERGE INTO Foo
USING (SELECT 2 AS V) AS Source ON 1 = 0
WHEN NOT MATCHED BY SOURCE THEN DELETE
WHEN NOT MATCHED BY TARGET THEN INSERT (V) VALUES (Source.V);
As a result, the trigger will be called twice for the MERGE. But both times, "SELECT * FROM Foo" delivers the fully updated data already: There will be one row with the value 2. The value 1 is deleted already.
This really surprised me: The insert-trigger is called first and the deleted row is gone from the data before the call to the delete-trigger happens.
Only the values of "inserted" and "deleted" correspond to the delete- or insert-statement.
You could try something like this:
The trigger would check for the existence of #temp table.
If it doesn't exist, it creates it with dummy data. It then checks if the recent values contain the same user (SPID) that is running now and if the last time it was triggered was within 20 seconds.
If these are true then it will PRINT 'Do Nothing' and drop the table, otherwise it will do your trigger statement.
At the end of your trigger statement it inserts into the table the SPID and current datetime.
This temp table should last as long as the SPID connection, if you want it to last longer make it a ##temp or a real table.
IF OBJECT_ID('tempdb..#temp') IS NULL
begin
Create table #temp(SPID int, dt datetime)
insert into #temp values (0, '2000-01-01')
end
If ##SPID = (select top 1 SPID from #temp order by dt desc)
and Convert(datetime,Convert(varchar(19),GETDATE(),121)) between
Convert(datetime,Convert(varchar(19),(Select top 1 dt from #temp order by dt desc),121)) and
Convert(datetime,Convert(varchar(19),DateAdd(second, 20, (select top 1 dt from #temp order by dt desc)),121))
begin
PRINT 'Do Nothing'
Drop table #temp
end
else
begin
--trigger statement
Insert into #temp values (##SPID, GETDATE())
end

Keyword 'Values' absent Oracle 9i

I'm trying to execute the following trigger when inserting some data in my table :
CREATE OR REPLACE TRIGGER AJOUTER_NEW_CONSISTANCE
AFTER INSERT OR UPDATE OF
CONSISTANCE_LIBELLE_1,CONSISTANCE_LIBELLE_2,CONSISTANC_LIBELLE_3
ON DB.ETAT_PARCELLAIRE
BEGIN
insert into DB.CONSISTANCE.LIBELLE
select consistance_libelle_1
from DB.ETAT_PARCELLAIRE
where DB.ETAT_PARCELLAIRE.consistance_libelle_1 not in (
select LIBELLE from DB.CONSISTANCE.LIBELLE);
END;
But it keeps giving me the following error :
PL/SQL : ORA00926 : Keyword Values absent.
How can I fix this ?
Thank you for help in advance :)
If CONSISTANCE is a table with a column called LIBELLE then you're referring to it incorrectly.
your insert is including the column, which I assume means the table has other columns and you only want to insert a value into that one, but your syntax is wrong (DB.CONSISTANCE.LIBELLE should be DB.CONSISTANCE(LIBELLE)). it is this line that's generating the ORA-00926.
your sub-select is including the column in the table name (DB.CONSISTANCE.LIBELLE should be just DB.CONSISTANCE)
So it should be:
CREATE OR REPLACE TRIGGER AJOUTER_NEW_CONSISTANCE
AFTER INSERT OR UPDATE OF
CONSISTANCE_LIBELLE_1,CONSISTANCE_LIBELLE_2,CONSISTANC_LIBELLE_3
ON DB.ETAT_PARCELLAIRE
BEGIN
insert into DB.CONSISTANCE(LIBELLE)
select consistance_libelle_1
from DB.ETAT_PARCELLAIRE
where consistance_libelle_1 not in (
select LIBELLE from DB.CONSISTANCE);
END;
I'm also not sure if CONSISTANC_LIBELLE_3 is a typo and it should be CONSISTANCE_LIBELLE_3.
You could also do a not exists instead of a not in:
insert into DB.CONSISTANCE(LIBELLE)
select CONSISTANCE_LIBELLE_1
from DB.ETAT_PARCELLAIRE
where not exists (
select 1
from DB.CONSISTANCE
where LIBELLE = DB.ETAT_PARCELLAIRE.CONSISTANCE_LIBELLE_1
);
Or use a merge:
merge into DB.CONSISTANCE c
using (select CONSISTANCE_LIBELLE_1 from DB.ETAT_PARCELLAIRE) ep
on (c.LIBELLE = ep.CONSISTANCE_LIBELLE_1)
when not matched then
insert (LIBELLE) values (ep.CONSISTANCE_LIBELLE_1);
Using a trigger to (partially) maintain that table looks odd though - it would be simpler to have a view which selects distinct values from ETAT_PARCELLAIRE:
create or replace view CONSISTANCE_VIEW as
select distinct CONSISTANCE_LIBELLE_1
from ETAT_PARCELLAIRE;
But they would have different content - once a value has appeared in CONSISTANCE_LIBELLE_1 it will always remain in CONSISTANCE as you are not removing defunct values, only inserting new ones; whereas CONSISTANCE_VIEW would only show values currently in the table. It isn't clear which behaviour you want.

How to keep in a database the number of calls of each record?

For example, I want to know at any moment most popular records that users searched in the database.
I expect that for each record I need to introduce a new number field. Thus, the record will be like this:
key - value - counter
How I can to increase the value of counter inside a database?
I think it's something like calling a stored procedure while a query, but I'm not sure. Perhaps the question is quite simple, I'm just a beginner and I apologize in that case.
You should use a trigger for this. Triggers are commands that execute on events, everytime an INSERT, UPDATE or DELETE statement is executed, even if their calls do not modify any records. Due tot this, you can't directly create a trigger for updating the count field of a record when you SELECT (read) it.
But, you can try a workaround in which you also have a date field in your table, and update it everytime a record is called. Use your application to send this datetime value to the database, which will trigger an UPDATE.
By making an UPDATE statement, your trigger is called and this way you can add your code to modify the count column.
CREATE TRIGGER tafter AFTER INSERT OR DELETE ON tbl1 FOR EACH ROW UPDATE SET counter = counter + 1 where key = 'keyval';
Firstly, this sounds like an awful performance problem. Every time you select a record you have to update it if you're tracking the selects with a single number, which just stores total selects, otherwise you have to insert timestamped values into another table to be able to analyse when the rows were read.
Anyway, you can do this with a common table expression in which you update a counter in the table and return the results to the main query: http://sqlfiddle.com/#!1/1aa41/6
Code something like:
create table my_table(col1 varchar(30), col2 numeric, select_count numeric);
insert into my_table values ('A',1,0);
insert into my_table values ('B',2,0);
insert into my_table values ('C',3,0);
insert into my_table values ('D',4,0);
insert into my_table values ('E',5,0);
with upd as (
update my_table
set select_count = select_count+1
where col1 = 'A'
returning *)
select *
from upd;
with upd as (
update my_table
set select_count = select_count+1
where col1 = 'B'
returning *)
select *
from upd;
with upd as (
update my_table
set select_count = select_count+1
where col1 = 'A'
returning *)
select *
from upd;
with upd as (
update my_table
set select_count = select_count+1
returning *)
select count(*)
from upd;
with upd as (
update my_table
set select_count = select_count+1
returning *)
select sum(col2)
from upd;
with upd as (
update my_table
set select_count = select_count+1
returning *)
select *
from upd;

Insert into a temporary table and update another table in one SQL query (Oracle)

Here's what I'm trying to do:
1) Insert into a temp table some values from an original table
INSERT INTO temp_table SELECT id FROM original WHERE status='t'
2) Update the original table
UPDATE original SET valid='t' WHERE status='t'
3) Select based on a join between the two tables
SELECT * FROM original WHERE temp_table.id = original.id
Is there a way to combine steps 1 and 2?
You can combine the steps by doing the update in PL/SQL and using the RETURNING clause to get the updated ids into a PL/SQL table.
EDIT:
If you still need to do the final query, you can still use this method to insert into the temp_table; although depending on what that last query is for, there may be other ways of achieving what you want. To illustrate:
DECLARE
id_table_t IS TABLE OF original.id%TYPE INDEX BY PLS_INTEGER;
id_table id_table_t;
BEGIN
UPDATE original SET valid='t' WHERE status='t'
RETURNING id INTO id_table;
FORALL i IN 1..id_table.COUNT
INSERT INTO temp_table
VALUES (id_table(i));
END;
/
SELECT * FROM original WHERE temp_table.id = original.id;
No, DML statements can not be mixed.
There's a MERGE statement, but it's only for operations on a single table.
Maybe create a TRIGGER wich fires after inserting into a temp_table and updates the original
Create a cursor holding the values from insert and then loop through the cursor updating the table. No need to create temp table in the first place.
You can combine steps 1 and 2 using a MERGE statement and DML error logging. Select twice as many rows, update half of them, and force the other half to fail and then be inserted into an error log that you can use as your temporary table.
The solution below assumes that you have a primary key constraint on ID, but there are other ways you could force a failure.
Although I think this is pretty cool, I would recommend you not use it. It looks very weird, has some strange issues (the inserts into TEMP_TABLE are auto-committed), and is probably very slow.
--Create ORIGINAL table for testing.
--Primary key will be intentionally violated later.
create table original (id number, status varchar2(10), valid varchar2(10)
,primary key (id));
--Create TEMP_TABLE as error log. There will be some extra columns generated.
begin
dbms_errlog.create_error_log(dml_table_name => 'ORIGINAL'
,err_log_table_name => 'TEMP_TABLE');
end;
/
--Test data
insert into original values(1, 't', null);
insert into original values(2, 't', null);
insert into original values(3, 's', null);
commit;
--Update rows in ORIGINAL and also insert those updated rows to TEMP_TABLE.
merge into original original1
using
(
--Duplicate the rows. Only choose rows with the relevant status.
select id, status, valid, rownumber
from original
cross join
(select 1 rownumber from dual union all select 2 rownumber from dual)
where status = 't'
) original2
on (original1.id = original2.id and original2.rownumber = 1)
--Only math half the rows, those with rownumber = 1.
when matched then update set valid = 't'
--The other half will be inserted. Inserting ID causes a PK error and will
--insert the data into the error table, TEMP_TABLE.
when not matched then insert(original1.id, original1.status, original1.valid)
values(original2.id, original2.status, original2.valid)
log errors into temp_table reject limit 999999999;
--Expected: ORIGINAL rows 1 and 2 have VALID = 't'.
--TEMP_TABLE has the two original values for ID 1 and 2.
select * from original;
select * from temp_table;