I have a set of SQL
files with complex SQL
(droping/creation tables and stored procedures with delimiters changes, droping/creation tables, altering tables etc). I try to run this files like:
$sql = file_get_contents("sql/filename.sql");
if (!$mysqli->multi_query($sql)) {
echo("Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error);
exit();
}
do {
if ($res = $mysqli->store_result()) {
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
Some files are processed normally, but on other files with delimiter changes and stored procedures creation I received an error:
Multi query failed: (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 'DELIMITER $$
DROP PROCEDURE IF EXISTS alter_members_table $$
CREATE PROCEDUR' at line 1
If I copy content of this SQL
file and execute it in phpMyAdmin
- all works fine, so I am sure that SQL
is correct.
What is wrong and how can I fix this?
UPDATE...
One of the SQL
files generated this error:
DELIMITER $$
DROP PROCEDURE IF EXISTS procedure_name $$
CREATE PROCEDURE procedure_name()
BEGIN
IF NOT EXISTS ((
SELECT * FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND COLUMN_NAME = 'column_name'
AND TABLE_NAME = 'table_name'
))
THEN
ALTER TABLE `table_name`
ADD COLUMN `column_name` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'
AFTER `other_column_name`;
END IF;
END $$
CALL procedure_name() $$
DELIMITER ;
Why I use stored procedure here, this is a part of the plugin installation script, it must execute few SQL files to prepare the DB. I have surfed for the solution, how to create new column only if it still not exists. I have found only procedural solution.