无法使用PREPARE和EXECUTE

时间:2012-10-26 12:32:22

标签: mysql sql

我首先检查表是否存在。如果不存在,那么我正在创造一个&然后将数据插入其中。

DELIMITER $$

DROP PROCEDURE IF EXISTS `myDb`.`InsertData`$$

CREATE DEFINER=`root`@`%` PROCEDURE `InsertData`(
IN _P1 VARCHAR(255),
IN _P2 DATETIME,
IN _P3 TEXT,
IN _TableName VARCHAR(255)
)
BEGIN
DECLARE TableCount INT(1);

SET TableCount = (SELECT COUNT(table_name)
FROM information_schema.tables
WHERE table_schema = 'myDb' AND table_name = _TableName);

IF(TableCount = 0) THEN
    SET @s = CONCAT('CREATE TABLE IF NOT EXISTS `myDb`.`',_TableName,'` ( 
     `P1` VARCHAR(255),`P2` DATETIME, `P3` TEXT ;'); 
    PREPARE stmt3 FROM @s; 
    SELECT stmt3;
    EXECUTE stmt3; 
END IF;
SET @s = CONCAT('INSERT INTO `myDb`.`',_TableName,'` ( P1, P2, P3)
VALUES (' + _P1 + ',' + _P2 + ',' + _P3 + ')'); 
PREPARE stmt3 FROM @s; 
EXECUTE stmt3; 

END$$

DELIMITER ;

程序编译成功,但是当我运行它时,它会给我错误:

Error Code : 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 '' at line 2

1 个答案:

答案 0 :(得分:1)

您错过了)

SET @s = CONCAT('CREATE TABLE IF NOT EXISTS `myDb`.`',_TableName,'` ( 
            `P1` VARCHAR(255),`P2` DATETIME, `P3` TEXT );'); 
                                                       ^----------here