小编典典
两者之间的主要区别是该IFNULL函数接受两个参数,如果不存在则返回第一个,如果NULL第二个则返回第二个NULL。
COALESCE函数可以采用两个或多个参数,并返回第一个非NULL参数,或者NULL如果所有参数均为null,例如:
SELECT IFNULL('some value', 'some other value');
-> returns 'some value'
SELECT IFNULL(NULL,'some other value');
-> returns 'some other value'
SELECT COALESCE(NULL, 'some other value');
-> returns 'some other value' - equivalent of the IFNULL function
SELECT COALESCE(NULL, 'some value', 'some other value');
-> returns 'some value'
SELECT COALESCE(NULL, NULL, NULL, NULL, 'first non-null value');
-> returns 'first non-null value'
更新: MSSQL做更严格的类型和参数检查。此外,它不具有IFNULL功能,而是ISNULL具有功能,该功能需要知道参数的类型。因此:
SELECT ISNULL(NULL, NULL);
-> results in an error
SELECT ISNULL(NULL, CAST(NULL as VARCHAR));
-> returns NULL
COALESCEMSSQL中的功能还要求至少一个参数为非null,因此:
SELECT COALESCE(NULL, NULL, NULL, NULL, NULL);
-> results in an error
SELECT COALESCE(NULL, NULL, NULL, NULL, 'first non-null value');
-> returns 'first non-null value'
2020-05-17