我想检查数据库中是否已存在位置条目,因此在事务中我使用选择。
从城市=“伦敦”且国家/地区代码=“GB”的位置选择@location_id := location_id;
但在此之后,如果 @location_id 不返回任何内容,我希望创建位置,否则我将使用现有的 @location_id。我想这样的事情可能会起作用。
delimiter $$
if @location_id is null then
select @location_id := max(location_id) from location;
set @location_id = @location_id + 1;
insert into location (location_id, city, country_code)
values(@location_id, "London", "GB");
end if; $$
delimiter ;
(澄清一下:location_id 是位置表中的自动递增整数值)
“if 语句”的这种用法可以在事务中工作,或者在采用 @location_id 或过程的函数中工作吗?
最佳答案
经过进一步调查,我意识到我必须使用过程,因为您无法在函数内进行选择。最后我的解决方案是:
delimiter $$
CREATE PROCEDURE location_processor(in _city varchar(20),
in _country_code varchar(2), out id int)
begin
select location_id into id from calendar.location
where city = _city and country_code = _country_code limit 0,1;
if id is null then
select @id := max(location_id) from calendar.location;
if @id is null then
set @id = 0;
end if;
set @id = @id + 1;
insert into calendar.location (location_id, city, country_code)
values(@id, _city, _country_code);
set id = @id;
end if;
end; $$
delimiter ;
我使用以下方式调用它:
call calendar.location_processor("London", "GB", @id);
select @id;
关于MySQL:在事务中,我可以在 IF 语句中使用 SELECT 的结果吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43431526/