Jun 21, 2017

SQLite: Using a table to loop

Loop

You want to create a table with lots of records for testing purposes - in SQL you could make a loop using something like this:

while (@i <= 10000)
 begin
  insert into table1 values ( 'field1' + cast (@i as char).
 'field2'+ cast (@i as char).
...
)
set @i+=1
end
go

Unfortunately in SQlite loops are not implemented - but you could use this trick instead
It will use a tIndex table, and a tRange table to generate some records in a tTarget table.

The tTarget table  is for the result:
create table target (i text);

This table will receive the result as text

tRange table

create table tRange (start, finish);
insert into tRange (1, 100) ;

And then afterward you can change the start and finish parameters using:
update tRange set start = 3 ;
update tRange set finish = 90 ;

tIndex table

This one is tricky because it has to contain as many records as possible - you will have to create this table via a Java program (see previous post) - by default there will be 10,000 records.

Now the Loop trick 

insert into tTarget(i)
select ('Record number '||tIndex.id)
from tIndex join tRange
on (tIndex.id >= tRange.start and tIndex.id <= tRange.finish) ;

This will generate Record Number + start ...  up to Record Number+ finish

No comments:

LinkWithin

Related Posts Plugin for WordPress, Blogger...