我正在尝试编写一种更新SQL,以便在不存在新列的情况下添加这些列。
我已经尝试了一些方法,但都不起作用。
如果我尝试一个If NOT EXISTS,我总是会得到一个我无法理解的语法错误。
IF NOT EXISTS(
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'nutzer'AND table_schema = 'restdb' AND column_name = 'api_nutzer')
THEN
ALTER TABLE `nutzer` ADD `api_nutzer` TINYINT;
END IF;
[SQL] IF NOT EXISTS( SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'nutzer'
AND table_schema = 'restdb'
AND column_name = 'api_nutzer') THEN
ALTER TABLE `nutzer` ADD `api_nutzer` TINYINT;
[Err] 1064 - 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 'IF NOT EXISTS( SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
' at line 1
如果我直接执行SELECT,我会得到一个结果
有人知道我的错误在哪里吗?
我使用MySQL Server版本8.0.22
我知道Exists子句可以在WHERE部分中使用
SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
如果行存在,请尝试重新构建捕获的查询
例如
<i>if( /*begin extra condition*/ Select 1 where exists
(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'nutzer'
AND table_schema = 'restdb'
AND column_name = 'api_nutzer') = 1 /*end extra condition*/) then
ALTER TABLE `nutzer` ADD `api_nutzer` TINYINT;</i>
感谢您的帮助,我为我的问题找到了解决方案。
DROP PROCEDURE IF EXISTS addCol;
CREATE PROCEDURE addCol(
IN tabelle VarChar(255),
IN spalte VarChar(255),
IN type VarChar(255)
)
BEGIN
IF NOT EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = tabelle
AND TABLE_SCHEMA = 'restdb'
AND COLUMN_NAME = spalte
)
THEN
SET @ddl = CONCAT(' alter table ', tabelle ,' ADD ', spalte, ' ', type);
PREPARE STMT FROM @ddl;
EXECUTE STMT;
END IF;
END