Create a function with optional arguments in MySQL

后端 未结 3 623
我在风中等你
我在风中等你 2020-12-17 08:57

I want to create a function with optional arguments in MySQL. For instance, I want to create function that calculates the average of its arguments. I create a function of fi

3条回答
  •  不知归路
    2020-12-17 09:51

    While far from an ideal solution, here's how I solved optional parameters for a concat function I needed:

    delimiter ||
    create function safeConcat2(arg1 longtext, arg2 varchar(1023))
     returns longtext
     return safeConcat3(arg1, arg2, '');
    ||
    
    create function safeConcat3(arg1 longtext, arg2 varchar(1023), arg3 varchar(1023))
     returns longtext
     return safeConcat4(arg1, arg2, arg3, '');
    ||
    
    create function safeConcat4(arg1 longtext, arg2 varchar(1023), arg3 varchar(1023), arg4 varchar(1023))
    returns longtext
      begin
          declare result longText;
          set result = concat(arg1, arg2, arg3, arg4);
          if( result is null) then
              set result=arg1;
          end if;
          return result;
      end
    ||
    

    Note: This means you have to call the method that corresponds to the number of args.

提交回复
热议问题