Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite loop statements?

Tags:

Is there any loop statements in SQLite like FOR .. in .. LOOP or something like that? I have two columns StartRange, EndRange and I need to insert whole sequence in other table. So if StartRange is 1 and EndRange is 3 it's necessary to make three inserts with value, contains 1, 2, 3.

like image 841
kseen Avatar asked Sep 10 '11 09:09

kseen


People also ask

Does SQLite support triggers?

SQLite trigger may be specified to fire whenever a DELETE, INSERT or UPDATE of a particular database table occurs or whenever an UPDATE occurs on one or more specified columns of a table. At this time, SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers.


1 Answers

You can make loops in SQL with recursive triggers. Using mu is too short's schema

sqlite> create table t (startrange int not null, endrange int not null); sqlite> insert into t values(1, 3); sqlite> create table target (i int not null); 

we need to enable recursive triggers in SQLite:

sqlite> PRAGMA recursive_triggers = on; 

Make a temporary trigger to loop up to the end of the range:

sqlite> create temp trigger ttrig    ...> before insert on target    ...> when new.i < (select t.endrange from t) begin    ...> insert into target values (new.i + 1);    ...> end; 

Kick it off:

sqlite> insert into target values ((select t.startrange from t)); sqlite> select * from target; 3 2 1 sqlite>  
like image 94
Doug Currie Avatar answered Sep 28 '22 11:09

Doug Currie