Skip to content
Advertisement

Return default rows from a function when first SELECT does not return rows

I have this function http://rextester.com/VIHMIG61446

and I’m looking a way to not repeat the whole query on the if, so I decided to use with as to store the result but it does not work for me http://rextester.com/MVMVA73088

How should I use with as?

Advertisement

Answer

The if-else logic can be avoided completely. The equivalent result can be written as a single query. The function BOOL_AND is an aggregate function that returns false if any of the values are false, otherwise it returns true.

The following query will work correctly even if multiple rows are matched with the lower(name) like '<namevalue>' condition, or if you have multiple default values.

As to why you get an error with IF EXISTS(temporal_result), that is not valid sql. It’s illegal to do such branching from within an sql statement. What you can do instead is to save the result of the first query into a temporary table, and do the if-else branching referring to the temporary table. A correct version of your stored procedure is below:

Note that it is necessary to drop the table at the end of the procedure.

Also note that postgresql ignores upper / lower cases in entity names unless quoted, so it is generally considered poor style to use camel case when naming tables / fields / functions.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement