How to loop SQL query in mysql? I have a SQL query as following:

SET @thedate := CURDATE();

create temporay table tmp1(
...
where thedate=@thedate
);

create temporay table tmp2(
...
where thedate=@thedate
);

delete from tbl1;

replace into tbl1(
select * 
from tmp1
inner join tmp2
);


I need to have a loop, that @thedate is from 2014-1-1 to today. For each day, a new tbl1 generate, I also need t record it as a tsv, I wrote a script to do it but, I do not know how to do it from 2014-1-1 to today. the script is as following:

now=$(date +"%Y%m%d")
mysql mydb -e "select * from tbl1"&gt;$now.tsv
Excuse the mess I am about to create, but here it goes ...

STEP 01

Create a file called /tmp/ProcessDate.sql which contains this

create temporary table tmp1(
...
where thedate=@thedate
);

create temporary table tmp2(
...
where thedate=@thedate
);

delete from tbl1;

replace into tbl1(
select * 
from tmp1
inner join tmp2
);


STEP 02

Create a Shell Script call /tmp/ProcessDays.sh which contains this

MYSQL_USER=root
MYSQL_PASS=rootpassword
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"

TS_NOW=`date +"%s"`
TS_NDX=1
TS_DAY=0

while [ ${TS_DAY} -lt ${TS_NOW} ]
do
    SQL="SELECT DATE(FROM_UNIXTIME((UNIX_TIMESTAMP(MAKEDATE(YEAR(NOW()),${TS_NDX})))))"
    DT=`mysql ${MYSQL_CONN} -ANe"${SQL}"`
    echo "SET @thedate = '${DT}';" &gt; /tmp/ProcessOneDay.sql
    cat /tmp/ProcessDate.sql &gt;&gt; /tmp/ProcessOneDay.sql
    OUTFILE=Data_${DT}.tsv
    mysql ${MYSQL_CONN} -AN &lt; /tmp/ProcessOneDay.sql
    mysql ${MYSQL_CONN} -AN"SELECT * FROM tbl" &gt; ${OUTFILE}
    (( TS_NDX++ ))
    SQL="SELECT UNIX_TIMESTAMP(MAKEDATE(YEAR(NOW(),1) + INTERVAL ${TS_NDX} DAY)"
    TS_DAY=`mysql ${MYSQL_CONN} -ANe"${SQL}"`
done


STEP 03 : GIVE IT A TRY !!!