我尝试创建以下格式的存储过程: 分隔符 $$
CREATE PROCEDURE `CreateInsertLocation` (tableName VARCHAR(255),ts BIGINT(20),systs INT(20),lat FLOAT,lon FLOAT)
BEGIN
DECLARE FoundCount INT;
SELECT COUNT(1) INTO FoundCount
FROM information_schema.tables
WHERE table_schema = 'DB'
AND table_name = tableName;
IF FoundCount = 1 THEN SET @sql = CONCAT('INSERT INTO ',tableName,'
(timestamp, lattitude, longitude,systime)
VALUES
(','ts','lat','lon','systs')');
PREPARE stmt FROM @sql;
EXECUTE stmt;
ELSE
SET @sql = CONCAT('CREATE TABLE `',tableName,'`(
`id` bigint(20) NOT NULL DEFAULT '0',
`timestamp` bigint(20) NOT NULL DEFAULT '0',
`lattitude` float NOT NULL DEFAULT '0',
`longitude` float NOT NULL DEFAULT '0',
`systime` bigint(20) DEFAULT NULL,
KEY `LocIdx` (`vtuId`,`timestamp`),
KEY `SysIdx` (`vtuId`,`systime`),
PRIMARY KEY (id)');
PREPARE stmt FROM @sql;
EXECUTE stmt;
SET @sql = CONCAT('INSERT INTO ',tableName,'
(timestamp, lattitude, longitude,systime)
VALUES
(','ts','lat','lon','systs')');
PREPARE stmt FROM @sql2;
EXECUTE stmt;
END
$$
DELIMITER ;
-- 当我尝试在 Mysql 5.7 中执行此查询时出现以下错误
ERROR 1064 (42000): 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 '');
PREPARE stmt FROM @sql;
EXECUTE stmt;
ELSE SET @sql = CONCAT' at line 10
任何人都可以帮助改进这个程序吗?
最佳答案
这应该有效。注意单引号的顺序,因为它可能会变得棘手。
DELIMITER $$
CREATE PROCEDURE `CreateInsertLocation` (tableName VARCHAR(255),ts BIGINT(20),systs INT(20),lat FLOAT,lon FLOAT)
BEGIN
DECLARE FoundCount INT;
SELECT COUNT(1) INTO FoundCount
FROM information_schema.tables
WHERE table_schema = 'DB'
AND table_name = tableName;
IF FoundCount = 1 THEN
SET @sql = CONCAT('INSERT INTO ',tableName,' (timestamp, lattitude, longitude,systime) VALUES (',ts, ',', lat, ',', lon, ',', systs, ')' );
PREPARE stmt FROM @sql;
EXECUTE stmt;
ELSE
SET @sql = CONCAT('CREATE TABLE `',tableName,'` (
`id` bigint(20) NOT NULL DEFAULT 0,
`timestamp` bigint(20) NOT NULL DEFAULT 0,
`lattitude` float NOT NULL DEFAULT 0,
`longitude` float NOT NULL DEFAULT 0,
`systime` bigint(20) DEFAULT NULL,
KEY `LocIdx` (`vtuId`,`timestamp`),
KEY `SysIdx` (`vtuId`,`systime`),
PRIMARY KEY (id) )' );
PREPARE stmt FROM @sql;
EXECUTE stmt;
END IF;
SET @sql = CONCAT('INSERT INTO ',tableName,' (timestamp, lattitude, longitude,systime) VALUES (',ts, ',', lat , ',', lon, ',', systs, ')');
PREPARE stmt FROM @sql;
EXECUTE stmt;
END
$$
DELIMITER ;
关于Mysql 5.7 存储过程报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49981501/