3

测试.sql:

SET @my_var = 50;

CREATE TABLE test_table (
    id SMALLINT NOT NULL,
    my_text VARCHAR(@my_var),
    PRIMARY KEY (id)
);

命令行交互:

mysql> source d:/test.sql;
Query OK, 0 rows affected (0.00 sec)

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
'@my_var),
    PRIMARY KEY (id)
)' at line 3

有没有办法做到这一点?

4

1 回答 1

2

CREATE TABLE除了将整个编译为字符串并执行它之外,我想不出其他方法:

SET @my_var = 50;

PREPARE sql FROM '
CREATE TABLE test_table (
    id SMALLINT NOT NULL,
    my_text VARCHAR(' + @my_var + '),
    PRIMARY KEY (id)
);
'
EXECUTE sql;
DEALLOCATE PREPARE sql;

它非常丑陋,但应该可以。

于 2012-08-19T23:05:15.183 回答