简体   繁体   中英

Mysql - transforming non-null values part 2

In this question I asked if Mysql have a function which receives two arguments and returns null if the first is null or the second argument otherwise. Somebody said in the comment section that such function doesn't exist. How can I define this function in Mysql, considering that it may receive arguments of any type and the return value can be null or of the same type of the second parameter? Is it even possible?

try this:

Select IF(ISNULL(arg1), null, arg2)

Read more about Comparison Functions and Operators and Control Flow Functions .

This is not possible, given your or requirements.

The arguments and return values of stored functions (written in SQL) and user-defined functions (written in C) are all statically typed.

Granted, MySQL is pretty flexible with implicit casting, but the values are typed nonetheless. Even if you were okay with implicit casting, a scenario where that would be preferable to the seemingly-obvious solution is difficult to imagine.

IF(foo IS NULL,foo,bar) would suffice for the purpose and preserve the underlying types correctly, and IF(foo IS NULL,NULL,bar) would be almost the same thing, though the type of foo would be lost (eg a "it's a NULL DATETIME").

You have previously rejected those, for reasons that are not intuitively obvious. When a purpose can be accomplished with built-ins, the motivation to reinvent the wheel is hard to understand.

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