开发者

Syntax error when trying to CREATE TABLE using session variables

开发者 https://www.devze.com 2023-03-25 18:29 出处:网络
The following works in a new MySQL session: CREATE DATABASE rand27818; USE rand27818; CREATE TABLE sessions (id INT NOT NULL AUTO_INCREMENT, session VARCHAR(128), PRIMARY KE开发者_开发问答Y(id));

The following works in a new MySQL session:

CREATE DATABASE rand27818;
USE rand27818;
CREATE TABLE sessions (id INT NOT NULL AUTO_INCREMENT, session VARCHAR(128), PRIMARY KE开发者_开发问答Y(id));
DROP DATABASE rand27818;

However, this--

SET @sesslen = 128;
CREATE DATABASE rand27818;
USE rand27818;
CREATE TABLE sessions (id INT NOT NULL AUTO_INCREMENT, session VARCHAR(@sesslen), PRIMARY KEY(id));
DROP DATABASE rand27818;

--does not; it returns:

"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 '@sesslen), PRIMARY KEY(id))' at line 1"

I've tried several combinations of with extra parentheses around the variable, removing the @ sign, assigning the variable after USEing the database etc. to no joy. (Not that I thought it would make any difference.) Using variables in INSERT statements and SELECTing variables seem to be fine, I'm only encountering a problem trying to CREATE.

I'm thinking this is a curiosity of my installation (MySQL bundled with XAMPP, in case that helps) or me missing something due to a conceptual misunderstanding on my part of MySQL. If the latter, could someone explain what I'm missing?


You should use prepared statements.

SET @sesslen = 128;
CREATE DATABASE rand27818;
USE rand27818;

SET @sql = CONCAT('CREATE TABLE sessions (id INT NOT NULL AUTO_INCREMENT, session VARCHAR(', @sesslen, '), PRIMARY KEY(id));');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
...


Try SET @sesslen := 128;

You define mysql values with := and not =

0

精彩评论

暂无评论...
验证码 换一张
取 消