简体   繁体   中英

Insert procedure in mysql with condition

I want to create a procedure for inserting a row with some condition. Am new for this field please any one help me to do this.

My Table structure is.

Id startDate enddate    transdate   status.
1  1/12/2012 30/12/2012 31/12/2013  CLOSED
2  1/1/2013  30/1/2013  31/1/2013   OPEN

My Query logic is here.

This procedure is run every day.But the procedure check the last entry that is id=2 and check the transaction date. if the transaction date less than the current date means.update the last record status as CLOSED and insert the new record automatically with the below last Record.

Id startDate enddate    transdate   status.
1  1/12/2012 30/12/2012 31/12/2013  CLOSED
2  1/1/2013  30/1/2013  31/1/2013   CLOSED
2  1/2/2013  27/2/2013  28/2/2013   OPEN

Any one help me to do this.

It's going to be something like this:

create procedure updatetable()   
BEGIN
    declare found_id as int;
    select id into found_id from table where transdate >= curdate() and status = 'open';
    if (!is_null( found_id )) THEN
       update table set status = 'closed' where id = found_id;
       insert into table( startdate, enddate, transdate, status ) 
           values concat( year(curdate()), "-01-", month(curdate())), 
                  concat( year(curdate()), "-", LAST_DAY( curdate()), month(curdate())), curdate(),
                  "open" );
    END IF

END

You'll need to debug this a bit as I'm just guessing the syntax. The intent is to check for any entries with transdate equal to or after the current date. If any are found then update that entry to be 'closed' and create a new entry with the first and last date of this month and status = 'open'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM