Search code examples
mysqlsqlselectstored-proceduresprepared-statement

Can I use 'LINES STARTING BY' and 'LINES TERMINATED BY' on the same query in MySQL?


I'm working on a procedure that copies some data into a text file using two prepared statements (@aux1 and @aux2). Then the table where the information is copied, get's all of it's rows deleted.

The issue is that when I execute the procedure using call copyIntoFile() I get an error.

PROCEDURE

delimiter !!
drop procedure if exists copyIntoFile !!
create procedure copyIntoFile()

begin
    declare path varchar(255);
    set path = concat("'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/", curdate(), ".txt'");

    set @aux1 = concat("select * from movie_modification where modified = true into outfile ", path, 
                        " fields terminated by ';' lines starting by 'Edit: ' lines terminated by '\n';");
    prepare stmt1 from @aux1;
    execute stmt1;
    deallocate prepare stmt1;

    set @aux2 = concat("select * from movie_modification where modified = false into outfile ", path, 
                        " fields terminated by ';' lines starting by 'New: ' lines terminated by '\n';");
    prepare stmt2 from @aux2;
    execute stmt2;
    deallocate prepare stmt2;

    delete from movie_modification;
end !!
delimiter ;

ERROR (When executing the procedure)

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'lines terminated by ' '' at line 1

As you can see, the error occurs near lines terminated by (at line 1). So now I'm wondering if I can use lines terminated by after lines starting by or if just one of this statements is accepted in each query.

What's wrong?


Solution

  • I think you need to replace this:

    select ...
    into outfile ...
    fields terminated by ';' lines starting by 'Edit: ' lines terminated by '\n'
    

    With:

    select ...
    into outfile ...
    fields terminated by ';' lines starting by 'Edit: ' terminated by '\n'
    

    That is: the lines keyword should not be repeated.