从文件创建 MySQL 存储过程


create mysql a stored procedure from file

我正在尝试使用PHP创建一个存储过程。 我的阅读表明了通过使用 PHP 中的"exec"命令运行.sql文件来执行此操作的最佳方法。

在测试中,我创建了一个名为 amtv3_create_routines.sql 的文件,其中包含以下内容:

DELIMITER //
DROP PROCEDURE IF EXISTS createTc //
CREATE PROCEDURE createTc()
BEGIN
    drop table if exists v3_tc;
    CREATE TABLE v3_tc (
        source BIGINT UNSIGNED NOT NULL ,
        dest BIGINT UNSIGNED NOT NULL ,
        PRIMARY KEY (source, dest) )
    ENGINE = InnoDB;
    insert into v3_tc (source, dest)
        select distinct rel.sourceid, rel.destinationid
        from rf2_ss_relationships rel inner join rf2_ss_concepts con
            on rel.sourceid = con.id and con.active = 1
        where rel.typeid = (select distinct conceptid from rf2_ss_descriptions where term = 'is a')
        and rel.active = 1;
    REPEAT
        insert into v3_tc (source, dest)
            select distinct b.source, a.dest
            from v3_tc a
            join v3_tc b on a.source = b.dest
            left join v3_tc c on c.source = b.source and c.dest = a.dest
            where c.source is null;
        set @x = row_count();
        select concat('Inserted ', @x);
    UNTIL @x = 0 END REPEAT;
    create index idx_v3_tc_source on v3_tc (source);
    create index idx_v3_tc_dest on v3_tc (dest);
END //
DELIMITER;

当我手动将其输入 mysql 5.6.22 时,此代码工作正常但是,如果我保存文件并从提示符输入命令。

mysql -uroot -p -hlocalhost amtv3  < [full path]/amtv3_create_routines.sql 

我尝试使用 utf8 编码和 windows 1252 编码保存文件。

在命令提示符下,没有反馈,并且不会创建过程。在PHP中,我使用的是codeigniter框架。如果我使用 db->query 方法,我可以创建存储过程,但是数据库会失去连接。发布$db->reconnect()有效,但不可靠。

关于如何创建存储过程的任何建议?

略最后一行中的空格,DELIMITER;应该会导致语法错误(可能还有其他原因导致此错误未打印)。

DELIMITER只是某些MySQL客户端的功能,而不是服务器的功能。因此,当直接执行.sql文件时,服务器会将第一个分号解释为第一个语句的结尾,DELIMITER //将被视为语法违规:

错误 1064:您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本对应的手册,了解在"分隔符//"附近使用的正确语法创建过程 . . .

在这里发现这个:https://github.com/go-sql-driver/mysql/issues/351#issuecomment-120081608

解决方案是什么?只是不要更改分隔符。BEGINEND 已经分隔复合语句。

源:https://www.tutorialspoint.com/mysql/mysql_begin_end_compound.htm

你可以试试这个

mysql -h localhost -U <username> -d <database_name> -f /home/user/<procedure_name>.sql