考虑:
SET @PREFIX='DEV_';
SET @REFRESHDB=CONCAT(@PREFIX,'Refresh');
CREATE TABLE @REFRESHDB.`Metadata`
(
`Key` VARCHAR(30) NOT NULL,
`Value` VARCHAR(30) NOT NULL,
PRIMARY KEY (`Key`)
) ENGINE = InnoDB;
INSERT INTO @REFRESDB.`Metadata` (`Key`, `Value`) VALUES ("Version", "0");
这似乎没有效果:mysql回来了:
您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在“@REFRESHDB .Metadata”附近使用正确的语法
据我所知,根据the documentation,我已经完成了正确的事情。然而MySQL表示不允许这样做。这是MySQL的一些限制(不允许使用变量作为标识符)还是别的什么?
答案 0 :(得分:8)
您必须使用prepare语句/动态sql来执行此操作。
本文详细介绍了这两个方面:
http://rpbouman.blogspot.com/2005/11/mysql-5-prepared-statement-syntax-and.html
试试这个:
SET @PREFIX='DEV_';
SET @REFRESHDB=CONCAT(@PREFIX,'Refresh');
SET @st = CONCAT('CREATE TABLE ', @REFRESHDB,'.`Metadata`
(
`Key` VARCHAR(30) NOT NULL,
`Value` VARCHAR(30) NOT NULL,
PRIMARY KEY (`Key`)
) ENGINE = InnoDB');
PREPARE tStmt FROM @s;
EXECUTE tStmt;
SET @s = CONCAT('INSERT INTO ', @PREFIX, '.`Metadata` (`Key`, `Value`) VALUES ("Version", "0")');
PREPARE stmt FROM @s;
EXECUTE stmt;
答案 1 :(得分:3)
文档说明:
“可以从一组有限的数据类型中为用户变量分配值:整数,十进制,浮点,二进制或非二进制字符串或NULL值”
您正在尝试将变量用作对象。这不受支持。
答案 2 :(得分:0)
我建议你写一个存储过程:
DELIMITER $$
CREATE PROCEDURE (IN DBname varchar(255)
, IN AKey varchar(255)
, IN AValue varchar(255))
BEGIN
DECLARE query VARCHAR(1000);
-- First check the DBName against a list of allowed DBnames,
-- to prevent SQL-injection with dynamic tablenames.
DECLARE NameAllowed BOOLEAN;
SELECT 1 INTO NameAllowed WHERE DBName IN ('validDB1','validDB2');
IF (NameAllowed = 1) THEN BEGIN
-- DBName is in the whitelist, it's safe to continue.
SET query = CONCAT('INSERT INTO '
,DBName
,'.MetaData (`key`,`value`) values (?,?));
-- note the use of parameter placeholders, to prevent SQL-injection.
PREPARE stmt FROM query;
EXECUTE stmt USING Akey, AValue;
DEALLOCATE PREPARE stmt; -- clears the query and its result from the cache.
END; END IF;
END $$
DELIMITER ;