Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate with before insert trigger in sqlite

I've been searching on the web how to use "before trigger" in sqlite. I know properly on using "after trigger". I found the one that said that "before trigger" was used to validate before any changes made to database (insert/updat row in table). To clear the expression, I wrote a trigger in which type is before and event is insert to validate mark before inserting. My trigger is

create trigger mark_insert before insert on exam
when mark<=50
begin
insert into exam(mark) values(50);
end; 

Maybe it is wrong trigger. So, could you please point me out the errors in it? I want to check the mark whether it is less than or equal 50. If so, I want to insert default value(in this case, 50). I'm not much familiar with sql and trigger and starting to learn.

My exam table has following columns,

id(pk) | subject | mark
like image 305
waiyan Avatar asked Nov 17 '11 20:11

waiyan


People also ask

Can I create CTE in trigger?

This means that CTE is valid only to the scope of the query. However, you can write a CTE inside a stored procedure or User Defined Functions (UDFs) or triggers or views. However, you cannot implement CTEs inside indexed views.

How many types of triggers are there in SQLite?

Action for the trigger, it is the sql statement. There is two SQLite extension to triggers 'OLD' and 'NEW'.


1 Answers

if you want to check the mark whether it is less than or equal 50

CREATE TRIGGER trigger_min_mark AFTER INSERT ON exam
WHEN New.mark<=50
BEGIN
  UPDATE exam SET mark=50 WHERE id = New.id;
END

Be carefull you in the when statement you must specify New.ColumnName

like image 166
Loukas Avatar answered Nov 15 '22 09:11

Loukas