MYSQL:创建具有多个返回的函数

时间:2018-01-15 09:10:26

标签: mysql function

为什么这个功能不起作用?

CREATE FUNCTION build_address(street VARCHAR(50), city VARCHAR(30), state CHAR(2), zipcode VARCHAR(10), country VARCHAR(10)) RETURNS VARCHAR(130)
    IF (street != '',
    IF (city != '',
    IF (state != '',
    IF (zipcode != '',
    IF (country != '',
    RETURN CONCAT(street, ', ', city, ', ', state, ' ', zipcode, ' ', country),
    RETURN CONCAT(street, ', ', city, ', ', state, ' ', zipcode)),
    RETURN CONCAT(street, ', ', city, ', ', state)),
    RETURN CONCAT(street, ', ', city)),
    RETURN CONCAT(street),
    IF (city != '',
    IF (state != '',
    IF (zipcode != '',
    IF (country != '',
    RETURN CONCAT(city, ', ', state, ' ', zipcode, ' ', country),
    RETURN CONCAT(city, ', ', state, ' ', zipcode)),
    RETURN CONCAT(city, ', ', state)),
    RETURN CONCAT(city),
    IF (state != '',
    IF (zipcode != '',
    IF (country != '',
    RETURN CONCAT(state, ' ', zipcode, ' ', country),
    RETURN CONCAT(state, ' ', zipcode)),
    RETURN CONCAT(state),
    IF (zipcode != '',
    IF (country != '',
    RETURN CONCAT(zipcode, ' ', country),
    RETURN CONCAT(zipcode),
    IF (country != '',
    RETURN CONCAT(country),
    RETURN '')))))))));

我大约99%确定括号在正确的位置。你可以仔细检查,但我不认为这是问题。我认为问题在于我因为有多个退货声明而对我感到生气,但它们都属于自己的范围。据我所知,这应该工作正常。

我不知道这是否重要,但我使用的是phpMyAdmin,它仍在MySQL 5.6.21上。

我收到以下错误:

  

1064 - 您的SQL语法出错;查看与您的MariaDB服务器版本相对应的手册,以便使用“RETURN CONCAT附近”(街道,',',城市,',',状态, '',zipcode,'',country),       RE'在第7行

1 个答案:

答案 0 :(得分:1)

您对https://www.raywenderlich.com/129059/self-sizing-table-view-cellsif function感到困惑。你需要后者。

另外,这种方式太过于不必要的复杂化了。没有理智的人会跟随那些疯狂的括号。这可以写得更简单:

create function build_address(
    street varchar(50),
    city varchar(30),
    state char(2),
    zipcode varchar(10),
    country varchar(10)
)
returns varchar(130) deterministic
begin
  declare ret varchar(130);
  declare sep varchar(10);

  set ret = '';
  set sep = '';

  if street is not null and street != '' then
    set ret = concat(ret, sep, street);
    set sep = ', ';
  end if;

  if city is not null and city != '' then
    set ret = concat(ret, sep, city);
    set sep = ', ';
  end if;

  if state is not null and state != '' then
    set ret = concat(ret, sep, state);
    set sep = ' ';
  end if;

  if zipcode is not null and zipcode != '' then
    set ret = concat(ret, sep, zipcode);
    set sep = ' ';
  end if;

  if country is not null and country != '' then
    set ret = concat(ret, sep, country);
    set sep = ' ';
  end if;

  return ret;
end;

顺便说一句 - 你读过if statement吗?试图将地址分成这样的组件主要是一个注定要失败的想法。 WILL 是那些无法以该格式填写地址的人。最好的方法是简单地提供一个文本区域,用户可以在其中填写自由形式的地址。