简体   繁体   中英

Concatenate two columns values

I am trying to concatenate two date columns, putting a - between the values.

Table:

Column A                | Column B
------------------------|-------------------------
2010-07-01 00:00:00.000 | NULL
NULL                    | 2011-01-12 00:00:00.000
2006-04-01 00:00:00.000 | 2010-05-31 00:00:00.000
NULL                    | NULL

Query:

select L.ColumnA + ' - ' + L.Column B AS [Dates] 
from abc L

It's showing all the fields NULL unless both the columns have some data like

2006-04-01 00:00:00.000-2010 - 05-31 00:00:00.000

However, the final output I need is:

[Dates]
--------------------
07/01/10 - 
04/01/06 - 05/31/10
 - 01/12/11
<blank (for nulls)>

You need to convert NULL values to empty strings. At the very least:

SELECT COALESCE(L.ColumnA, '') + '-' + COALESCE(L.ColumnB, '') AS [Dates] 
    FROM abc L

Then, to format the dates as shown:

SELECT COALESCE(CONVERT(CHAR(8), L.ColumnA, 1), '') + '-' 
     + COALESCE(CONVERT(CHAR(8), L.ColumnB, 1), '') AS [Dates] 
    FROM abc L

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