好的,这是我第一次尝试CREATE FUNCTION,所以请容忍我!
因此,我有(简化的)表结构:
CREATE TABLE `pokemon` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`userid` INT UNSIGNED NOT NULL,
`boxid` TINYINT UNSIGNED NOT NULL DEFAULT 255,
`boxpos` SMALLINT UNSIGNED,
PRIMARY KEY (`id`),
UNIQUE KEY `position` (`userid`,`boxid`,`boxpos`)
) ENGINE=InnoDB我想要创建一个函数,在给定用户ID和框ID的情况下,返回一个空框位置(即。不会触发一个重复的键错误)。
请注意,boxid对方框ID使用0到249之间的值,对用户方使用255作为特殊值。boxpos在方框中可以从0到45,504不等,但在党内只有0到5。另外,在党中,返回的位置应该是第一个空的位置,而在一个盒子里应该是一个随机的位置。
因此,考虑到这一切,我的尝试是:
begin
declare ret smallint unsigned;
declare exist tinyint unsigned default 1;
if fieldid = 255 then
create temporary table `party` (
`pos` smallint unsigned not null
);
insert into `party` values (0),(1),(2),(3),(4),(5);
delete from `party` where `pos` in (select `fieldpos` from `pokemon` where `userid`=userid and `fieldid`=255);
select `pos` into ret from `party` limit 1;
if ret is null then select `[[Error: No room in Party]]` from `party`; end if;
else
while exist=1 do
set exist=0;
set ret=floor(rand()*45504);
select 1 into exist from `pokemon` where `fieldid`=fieldid and `userid`=userid and `fieldpos`=ret;
end while;
end if;
return ret;
end;(注意,这是函数的主体,输入到phpMyAdmin中)
编辑:我已经修复了DECLARE问题,但是现在它说我不能从函数返回一个结果集。
我不知道我哪里出了问题,我想我需要帮助我走上正确的轨道。特别是,我一开始就有正确的功能逻辑吗?
发布于 2013-01-06 09:00:40
在这一行:
if ret is null then select `[[Error: No room in Party]]` from `party`; end if;您可以从party表中为所有行选择一个常量值,但不要将该选择的结果放入变量中。这可能就是错误的来源。
可能应该是这样的:
if ret is null then
set ret = '[[Error: No room in Party]]';
end if;(还需要注意的是,字符串文本需要用单引号(')括起来,而不是那些可怕的回标--这在一开始并不是必要的,所以最好把它们放在一起。)
https://stackoverflow.com/questions/14180588
复制相似问题