简体   繁体   中英

Mysql function to transform non-null values

I want to know if mysql have a function which receives two arguments, if the first is null, it returns null otherwise it returns the second.

It would be a shortcut for if(something is null, null, anotherthing) .

Unfortunately there is no function for yor behavior, but it is simple to create your own function if you have the permissions for that, other wise you could also add an IF THEN ELSE to your query like you already showed but that would be no answer for your question. If you want to create a function then you will have the problem that you need explicit parameter types and with mysql it is unfortunately also not functional to overload a function (same function name but different parameter types). So you need for different types different functions with different function names. It would look like that:

    CREATE FUNCTION `fmap_varchar`(e1 VARCHAR(255), e2 VARCHAR(255) )
    RETURNS VARCHAR(255) DETERMINISTIC
    RETURN IF(e1 IS NULL, NULL, e2);

You would have maybe also to take care for the correct charset which you can also specify at the returns clause.

And the solution with a query you gave already:

    SELECT IF(something IS NULL, NULL, anotherthing) FROM your_table;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM