Postgres: define a default value for CAST failures?

前端 未结 2 1109
感动是毒
感动是毒 2020-12-14 01:44

Is it possible to define a default value that will be returned in case a CAST operation fails?

For example, so that:

SELECT CAST(\'foo\'         


        
2条回答
  •  清歌不尽
    2020-12-14 02:07

    Trap the error as described in documentation and then specify an action to do instead.

    Documentation on error trapping for PostgreSQL Snippet included below.

    35.7.5. Trapping Errors

    By default, any error occurring in a PL/pgSQL function aborts execution of the function, and indeed of the surrounding transaction as well. You can trap errors and recover from them by using a BEGIN block with an EXCEPTION clause. The syntax is an extension of the normal syntax for a BEGIN block:

    [ <

    If no error occurs, this form of block simply executes all the statements, and then control passes to the next statement after END. But if an error occurs within the statements, further processing of the statements is abandoned, and control passes to the EXCEPTION list. The list is searched for the first condition matching the error that occurred. If a match is found, the corresponding handler_statements are executed, and then control passes to the next statement after END. If no match is found, the error propagates out as though the EXCEPTION clause were not there at all: the error can be caught by an enclosing block with EXCEPTION, or if there is none it aborts processing of the function.

提交回复
热议问题