0

好的,这是我第一次尝试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使用从 0 到 249 的值作为框 ID,并使用 255 作为用户方的特殊值。boxposBoxes 中的范围为 0 到 45,504,但 Party 中只有 0 到 5。此外,在 Party 中返回的位置应该是第一个空位置,而在 Box 中它应该是随机位置。

因此,考虑到所有这些,这是我的尝试:

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问题,但现在它说我不能从函数返回结果集。

我不确定我哪里出错了,我想我需要帮助才能走上正轨。特别是,我是否首先得到了正确的功能逻辑?

4

1 回答 1

1

在这一行:

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;

(另请注意,字符串文字需要用单引号 ( ') 括起来,而不是那些可怕的反引号 - 这首先不是必需的,因此最好将它们一起排除)。

于 2013-01-06T09:00:40.003 回答