How to use a declared variable as a path in MySQL?

user157629 :

I am working on a stored procedure that inserts some data in a text file.

The procedure has the following structure:

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

begin

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

    select * from movie_modification where modified = true
    into outfile path;   //<-- This return an error

end !!
delimiter ;

As you can see, I declared the path instead of just writing it next to into outfile because path has to be named as the current date and to make that I use curdate() function in the path declaration.

As the format I wrote for the select into outfile is wrong (it expects a text not a variable), how can I make it so it accepts a variable?

nbk :

You have two small problems.

first your Path has to be a string as you use double quotes you add at the start a single quote and at the end of path.

The other thing is to use prepared statentsfor your query

DELIMITER $$
DROP PROCEDURE IF EXISTS insertIntoFile§§
CREATE DEFINER=`root`@`localhost` PROCEDURE `insertIntoFile`()
BEGIN

    DECLARE path VARCHAR(255);
    SET path = CONCAT("'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/", curdate(), ".txt;'");

    SET @sql = CONCAT('select * from movie_modification where modified = true
    into outfile ',path);  

PREPARE test FROM @sql;
EXECUTE test;

end$$
DELIMITER ;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=401679&siteId=1