连接两列值

时间:2011-03-31 15:07:43

标签: sql sql-server sql-server-2005 tsql sql-server-2008

我正在尝试连接两个date列,在值之间加上-

表:

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

查询:

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

它显示所有字段为NULL,除非两列都有一些数据,如

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

然而,我需要的最终输出是:

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

1 个答案:

答案 0 :(得分:4)

您需要将NULL值转换为空字符串。至少:

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

然后,如图所示格式化日期:

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