gpt4 book ai didi

mysql - 使用 IF 启动 mysql 查询

转载 作者:行者123 更新时间:2023-11-29 00:17:50 25 4
gpt4 key购买 nike

根据 mysql 网站,我应该能够使用 if 语句启动查询。

IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF

但是当我尝试这个查询时

if (count(1)
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = 'dbname'
AND TABLE_NAME='tblname'
AND CONSTRAINT_NAME = 'con_name')
then
alter table table drop foreign key constraint_name;
end if

我得到一个语法错误,说我在“IF”附近有错误的语法,mysql workbench 突出显示 if 说语法错误,意外的 if。

我尝试过使用 begin if,并省略了 begin 和 end if,但错误始终相同。

最佳答案

您不能在语句外使用 ifwhile 条件,除非它们包含在 begin 的代码块中 - 结束。因此,数据库引擎在您的声明中抛出了一个错误。

要使您的语句生效,您需要一个存储过程并对语句进行一些更改。

示例:

delimiter //

drop procedure if exists drop_constraint //

create procedure drop_constraint(
in dbName varchar(64),
in tableName varchar(64),
in constraintName varchar(64) )
begin
declare cnt int default 0;

select count(1) into cnt
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where
table_schema = dbName
and table_name = tableName
and constraint_name = constraintName;

-- now check if any found
if ( cnt > 0 ) then -- if found some
-- now, execute your alter statement
-- include your alter table statement here
end if;
end;
//

delimiter ;

使用上述过程,您可以检查和删除约束。

mysql> call drop_constraint( 'test', 'my_table', 'fk_name' );

关于mysql - 使用 IF 启动 mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22294891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com