0

Below is the code I have as part of a sqlalchemy query. Most of the time fist name is null. But Here in the case of below statement, always returns last name with a comma. Eg: lastName, How to add comma only if there's first name?

(func.isnull(
            prv.last_name,
            '') +
         ', ' +
         func.isnull(
            prv.first_name,
            '')).label('MyName')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Murali Uppangala
  • 884
  • 6
  • 22
  • 49

1 Answers1

1

I don't know what database you use behind sqlalchemy but I believe what you are looking for is an equivalent of MySQL's CONCAT_WS

CONCAT_WS() stands for Concatenate With Separator and is a special form of CONCAT(). The first argument is the separator for the rest of the arguments. The separator is added between the strings to be concatenated. The separator can be a string, as can the rest of the arguments. If the separator is NULL, the result is NULL.

Using it in sqlalchemy should be a matter of calling

func.CONCAT_WS(',', prv.last_name,prv.first_name) (example)

bagerard
  • 5,681
  • 3
  • 24
  • 48