IF function in H2 for MySQL compatibility

倖福魔咒の 提交于 2019-12-04 18:29:38

问题


I'm using H2 (with MySQL compatibility mode) to write some automated tests against our software that uses MySQL. Unfortunately, it seems like H2 does not have have the IF function that many of our queries use. Short of rewriting our application queries with something like DECODE, is their a good way to create the if function, say as an Alias?

The error that I'm getting:

WARNING: Failed to execute: SELECT IF(true,'TRUE!!','FALSE!!!') because: Function "IF" not found; SQL statement:

回答1:


Ended up just rewriting queries to use functions compatible with both database - H2, MySql. In my case, the functions in question were replaced with IFNULL.




回答2:


Yes you can create the if function as an alias:

CREATE ALIAS IF NOT EXISTS `IF` AS $$
    String ifFunction(boolean condition, String exp1, String exp2){
        if(condition) {
            return exp1;
        } else {
            return exp2;
        }
    }
$$;



回答3:


I've just had the same issue, and I resolved it with CASE/WHEN/THEN SQL statement. So you can rewrite your query as follows:

SELECT CASE WHEN true THEN 'TRUE!!' ELSE 'FALSE!!!' END;

Surely it's more verbose, but it fits both H2 and MySQL.



来源:https://stackoverflow.com/questions/27494009/if-function-in-h2-for-mysql-compatibility

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!