[英]MySQL - Using SELECT for IF statement condition in stored procedure
I want to execute, in a stored procedure, a certain set of statements if, in table my_table
there is exactly one row with value value
in column column_name
. 我想在存储过程中执行一组特定的语句,如果在表
my_table
中恰好有一行具有column_name
列中的value value
的行。 I have tried the following, but I get a syntax error: 我已经尝试了以下方法,但是出现语法错误:
IF ((SELECT COUNT(*) FROM my_table WHERE column_name = value) = 1) THEN
BEGIN
END;
END IF;
For context: In my procedure I create a temporary table at some point, where I store a list of values. 对于上下文:在我的过程中,我有时会创建一个临时表,用于存储值列表。 Then later on in the procedure, I want to check if a given value is present in that temporary table.
然后,在该过程的后面,我想检查该临时表中是否存在给定值。
I think you might be better to structure it more like this 我认为您最好像这样构造它
BEGIN
DECLARE myCOUNT INTEGER;
SELECT COUNT(*)
INTO myCount
FROM my_table
WHERE column_name=value;
IF (myCount = 1) THEN
-- do stuff
END IF;
END;
I'm not sure what you are trying to do, but I'll guess an "upsert" -- update a record if it exists, otherwise insert a new record. 我不确定您要做什么,但是我猜是“ upsert”-更新一条记录(如果存在),否则插入一条新记录。
In any case, if you are trying to ensure that name
is unique in my_table
, then this is not the right approach at all. 无论如何,如果您试图确保
name
在my_table
是唯一的,那么这根本不是正确的方法。 Instead, declare a unique index/constraint so the database ensures the data integrity: 而是声明一个唯一的索引/约束,以便数据库确保数据完整性:
create unique index unq_my_table_name on my_table(name);
You can then use insert . . . on duplicate key update
然后,您可以使用
insert . . . on duplicate key update
insert . . . on duplicate key update
insert . . . on duplicate key update
to modify the records in the database. insert . . . on duplicate key update
以修改数据库中的记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.