简体   繁体   中英

Oracle SQL - combine two columns

How can I combine two columns in Oracle SQL without using CASE ?

I have to combine FirstName and LastName in the same row.

I have a table as below:

FirstName     LastName
-----------------------
Ken           Chan
John          Ng
Joe           Lam

The data type of these columns is VARCHAR2 .

I try to apply the code as follow

SELECT 
    CONCAT(LastName, ‘,’, FirstName) AS FullName 
FROM
    LIST 
ORDER BY 
    Place;

SELECT 
    LastName, ‘,’, FirstName AS FullName 
FROM
    LIST 
ORDER BY
    Place;

But both of them result in the the same error

ORA-00909: invalid number of arguments.

May I also ask how can I not adding the ',' while there is missing LastName or FirstName?

Such as not adding ',' when there is only having LastName Chan. The FullName only display as Chan but not ,Chan.

Thanks a lot for helping me.

Use Concatenation Operator that is || . It concatenates character strings and results in another character string.
To make , comma optional in case if any of the LastName or firstName field is empty or null, use CASE statement.

Solution for your problem:

SELECT LastName || (CASE WHEN LastName IS NOT NULL AND FirstName IS NOT NULL THEN ',' END) || FirstName as FullName
FROM LIST
ORDER BY place;

Working Example: db<>fiddle Link

For more info on Concatenation Operator follow below link to official docs:

https://docs.oracle.com/cd/B19306_01/server.102/b14200/operators003.htm

Oracle's implementation of the concat() function only permits 2 parameters, and you have tried 3, that is why you got the error message.

It is simpler, in Oracle, to use the more traditional double pipe operator to form a concatenated string.

SELECT LastName || ‘,’ || FirstName as FullName 
from LIST 
order by Place;

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