在 MySQL 存储过程中使用用户定义变量设置表名
我想创建一个表,其名称取自用户定义的变量。以下代码似乎不起作用(我在 CREATE TABLE 行附近收到 MYSQL 语法错误)
提前感谢您的帮助
SET @ratingsNewTableName = CONCAT('ratings_', 'anotherString');
CREATE TABLE IF NOT EXISTS @ratingsNewTableName (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NOT NULL,
`movie_id` INT(11) NOT NULL,
`rate` DOUBLE NOT NULL,
`date` DATE NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
I want to create a table with a name taking from a user-defined variable. The following code doesn't seem to work (I get a MYSQL syntax error near CREATE TABLE line)
Thanks in advance for the help
SET @ratingsNewTableName = CONCAT('ratings_', 'anotherString');
CREATE TABLE IF NOT EXISTS @ratingsNewTableName (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NOT NULL,
`movie_id` INT(11) NOT NULL,
`rate` DOUBLE NOT NULL,
`date` DATE NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不是您问题的答案,但我认为这是一个坏主意。它会带来大量的麻烦。
您必须处理表名称中的特殊字符和编码
您必须过滤掉表名中禁止使用的字符
可用字符的范围将取决于底层文件系统的能力,因为 mySQL 使用表名创建其数据文件
您可能会遇到长期麻烦,因为 mySQL 在不同系统上对待表的方式不同。区分大小写由底层文件系统决定(表名在 Linux/Unix 上区分大小写,在 Windows 上不区分大小写)
我不会这样做。我宁愿拥有一张大表和一张较小的用户表。我会将用户指定的变量保留在用户表中,并在巨大的表中保留所有用户的所有记录,并通过“用户”键进行区分。
Not an answer to your question, but I think this is a bad idea. It invites heaps of trouble.
You'll have to deal with special characters and encodings in the table name
You'll have to filter out characters forbidden in a table name
The range of usable characters will depend on the abilities of the underlying file system, because mySQL creates its data files using the table name
You may run into long-term trouble because mySQL treats tables differently on different systems. Case sensitivity is dictated by the underlying file system (Table names are case sensitive on Linux/Unix, insensitive on Windows)
I wouldn't do this. I'd much rather have one huge table, and a smaller user table. I'd keep the user specified variable in the user table, and have all records for all users in the huge table, told apart by a "user" key.