我正在尝试添加一个列,如果它不存在并填充它。我的查询如下
IF NOT EXISTS (
SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'table_name'
AND TABLE_NAME = 'adapter'
AND COLUMN_NAME = 'adapter_ip'
)
BEGIN
ALTER TABLE `adapter` ADD `adapter_ip` varchar(15) NOT NULL DEFAULT '192.168.194.57';
UPDATE `adapter` SET `adapter_ip` = '192.168.194.57';
END;
但每次我都会收到错误。我究竟做错了什么?我测试过,如果我跑了
SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'table_name'
AND TABLE_NAME = 'adapter'
AND COLUMN_NAME = 'adapter_ip'
然后它起作用。一旦我把它放入if语句,它就会在第1行给出错误,说法语错误。因此,我甚至尝试用BEGIN
替换THEN
,但这也无效。知道可能导致这种情况的原因吗?感谢任何人的帮助。
答案 0 :(得分:0)
我认为您错过了THEN
,END IF
IF <condition>
此外,此链接看起来不错:http://www.cryer.co.uk/brian/mysql/howto_add_column_unless_exists.htm
答案 1 :(得分:0)
IF的语法是if(test-expr,then-expr,else-expr),详见此处:http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html