1

我需要根据插入另一个主表的最后一个 id 创建一个表,为此我创建了以下存储过程:

CREATE PROCEDURE `sp_create_campaign`
(
        IN  p_vName         VARCHAR(70),
        IN  p_iIdOper       INT(11),
        IN  p_iIdCount      INT(11),
        IN  p_iIdMoney      INT(11),
        IN  p_cPrefix       CHAR(2),
        IN  p_tComment      TINYTEXT,
        IN  p_iIdUser       VARCHAR(32),
        OUT p_return_code   TINYINT UNSIGNED
)
BEGIN

    DECLARE p_campaign INT(11);

    DECLARE exit handler for sqlexception
    BEGIN
        -- ERROR
            set p_return_code = 1;
            rollback;
    END;

    DECLARE exit handler for sqlwarning
    BEGIN
            -- WARNING
            set p_return_code = 2;
            rollback;
    END;

    START TRANSACTION;

        -- Campaign
        INSERT INTO `db_campaign` 
            (`vName`, `iIdOper`, `iIdCount`, `iIdMoney`, `cPrefix`, `tComment`, `iIdUser`, `dRegister`)
            VALUES
            (p_vName, p_iIdOper, p_iIdCount, p_iIdMoney, p_cPrefix, p_tComment, p_iIdUser, NOW());

        SET p_campaign := LAST_INSERT_ID();

        -- Sales
        SET @s = CONCAT('DROP TABLE IF EXISTS ', 'db_sale_', p_campaign);
        PREPARE stm FROM @s;
        EXECUTE stm;

        SET @x = CONCAT(
                'CREATE TABLE ',
                'db_sale_', p_campaign,
                "(
                `iIdSale`           INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
                `dDate`             DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
                `dSubtotal`         DECIMAL(7,2) UNSIGNED NOT NULL DEFAULT '00.00',
                `dTax`              DECIMAL(7,2) UNSIGNED NOT NULL DEFAULT '00.00',
                `dTotal`            DECIMAL(7,2) UNSIGNED NOT NULL DEFAULT '00.00',
                `iIdMoney`          INT(11) UNSIGNED NOT NULL,
                `iIdOper`           INT(11) UNSIGNED NOT NULL,
                `iIdBankCount`      INT(11) UNSIGNED NOT NULL,
                `iIdGroup`          INT(11) UNSIGNED NOT NULL,
                `iIdUser`           INT(11) UNSIGNED NOT NULL,
                `iIdUserReg`        VARCHAR(32) NOT NULL,
                `dRegister`         DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
                PRIMARY KEY (`iIdSale`)
                ) ENGINE=MyISAM DEFAULT CHARSET=utf8;");        

        PREPARE stm FROM @x;
        EXECUTE stm;

    COMMIT;

    -- SUCCESS
    set p_return_code = 0;

END

但问题是只插入第一条记录,建表失败。我哪里失败了?

4

4 回答 4

4

替换这一行:SET p_campaign := LAST_INSERT_ID();

有了这个:SELECT LAST_INSERT_ID() INTO p_campaign ;

于 2015-04-10T10:56:11.163 回答
0

两件事情:

  1. 执行DROP将隐含COMMIT您的交易。

  2. 尝试添加

    DEALLOCATE PREPARE stm;

在每个EXECUTE语句之后。

于 2012-07-19T15:36:41.357 回答
0

如果你使用SET你需要=而不是:=

于 2012-07-19T15:33:34.590 回答
0

根据last_insert_id()的 MySQL 文档

如果存储过程执行更改 LAST_INSERT_ID() 值的语句,则更改后的值会被过程调用之后的语句看到。

使用类似的东西:

SELECT id INTO p_campaign FROM db_campaign ORDER BY id DESC LIMIT 1;

或者:

SELECT max(id) INTO p_campaign FROM db_campaign;

于 2018-06-18T13:55:26.033 回答