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

wqsoz72f  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(256)

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

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,它仍然在MySQL5.6.21上。
我得到以下错误:
1064-您的sql语法有错误;检查与您的mariadb服务器版本相对应的手册,以了解在第7行“return concat(street,,,city,,,state,,,zipcode,,,country),re”附近使用的正确语法

bfnvny8b

bfnvny8b1#

你把if函数和if语句搞混了。你需要后者。
而且,这太复杂了。没有一个理智的人会追随那些疯狂的括号。这可以写得简单得多:

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;

顺便问一下-你读过程序员相信地址的谎言吗?试图将地址拆分成这样的组件基本上是一个注定要失败的想法。会有人不能用那种格式填写他们的地址。最好的方法是提供一个文本区域,用户可以在其中自由填写地址。

相关问题