I an trying to create stored procedure in following format : 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;
SET @sql = CONCAT('INSERT INTO ',tableName,'
(timestamp, lattitude, longitude,systime)
VALUES
(','ts','lat','lon','systs')');
PREPARE stmt FROM @sql2;
EXECUTE stmt;
END
$$
DELIMITER ;
-- When I am trying to execute this query in Mysql 5.7 I am getting following error
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
Can anyone help to improve this sotred procedure ?
This should work. Pay attention to order of single quotes as it can get tricky.
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 ;