Mysql过程定期将数据从一个数据库移动到另一个数据库

时间:2014-11-10 10:32:30

标签: mysql database stored-procedures rdbms

我正在尝试动态地完成以下事情。

基本目标是将记录从第一个数据库表移动到第二个数据库表。 数据库表名称始终因轮换而更改。 此外,记录会在第一个表中定期添加,因此我希望定期调用此过程 带有参数的第一个表,第二个表和来自第二个表的最后一个元素的特殊db1 id。所以使用这个id,我只能插入新的条目。

为此,我试图编写这样的程序。数据库是mysql。

DROP PROCECURE IF EXISTS `foo_bar`;

DELIMITER $$

CREATE PROCEDURE `foo_bar`(IN var_dbtable1 varchar(50), IN var_dbtable2 varchar(50))
BEGIN

    --get db1_id of last record from second table    
    DECLARE v_lst_db1_id bigint(21);

    SET @query1 = CONCAT("SELECT id INTO ", v_lst_db1_id, " FROM ", var_dbtable2, " ORDER BY id DESC LIMTI 1");
             PREPARE stmt1 from @query1;
             EXECUTE stmt1;
             DEALLOCATE PREPARE stmt1;

    -- insert records in db2 from db1 whose ids are greater than last id.
    SET @query2 = CONCAT("INSERT INTO ", var_dbtable2, "(col1, col2, col3)
            SELECT co1, col2, col3
            FROM ", var_dbtable1, " WHERE id > ", v_lst_db1_id, "");
            PREPARE stmt2 from @query2;
            EXECUTE stmt2;
            DEALLOCATE PREPARE stmt2;

END $$

DELIMTER ;

后来我想调用这个程序

call foo_bar("foo.foo1", "bar.bar1");

但这个程序似乎有问题。特别是首次查询的一部分。我错过了什么吗?

提前致谢。

更新: 错误消息:

您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以获得正确的语法,以便在' NULL'附近使用在第1行

2 个答案:

答案 0 :(得分:1)

试试这样:

SET @query1 = CONCAT("SELECT id INTO v_lst_db1_id FROM ", var_dbtable2, " ORDER BY id DESC LIMTI 1");
         PREPARE stmt1 from @query1;
         EXECUTE stmt1;
         DEALLOCATE PREPARE stmt1;

您想要使用变量,而不是变量所持有的值。在这种情况下null

您的查询已经

SELECT id INTO NULL FROM ...

答案 1 :(得分:0)

以下是完整的工作解决方案。谢谢`fancyPants'。

DROP PROCECURE IF EXISTS `foo_bar`;

DELIMITER $$

CREATE PROCEDURE `foo_bar`(IN var_dbtable1 varchar(50), IN var_dbtable2 varchar(50))
BEGIN

    --get db1_id of last record from second table    
    SET @v_lst_db1_id bigint(21) := 0;

    SET @query1 = CONCAT("SELECT id INTO @v_lst_db1_id FROM ", var_dbtable2, " ORDER BY id DESC LIMTI 1");
             PREPARE stmt1 from @query1;
             EXECUTE stmt1;
             DEALLOCATE PREPARE stmt1;

    -- insert records in db2 from db1 whose ids are greater than last id.
    SET @query2 = CONCAT("INSERT INTO ", var_dbtable2, "(col1, col2, col3)
            SELECT co1, col2, col3
            FROM ", var_dbtable1, " WHERE id > ", @v_lst_db1_id, "");
            PREPARE stmt2 from @query2;
            EXECUTE stmt2;
            DEALLOCATE PREPARE stmt2;

END $$

DELIMTER ;

此链接也很有用,

Using select into local variable and prepared statement in mysql