有没有办法在CREATE TABLE语句中使用用户定义的变量作为列长度?

时间:2012-08-19 22:52:34

标签: mysql sql varchar create-table user-variables

TEST.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

有办法做到这一点吗?

1 个答案:

答案 0 :(得分: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;

它非常难看,但应该有用。