连接 t-sql 中的列,但排除 null 列


SELECT 'Column 1: ' + t.Column1 + 
'Column 2: ' + t.Column2 + 
'Column 3: ' + t.Column3 
from Table1 t

所以我需要在每列之前都有一个自定义字符串,如图所示。但是,例如,如果 Column2 为空,我想排除整个部分"Column 2: ' + t.Column2。

其中仅显示非空列的子句不是我要找的,因为对于某些行,所有 3 列都是空的,这是有效的。

在 SQL Server 中,将null连接到字符串将导致null。利用这一事实,您可以执行以下操作:

SELECT ISNULL('Column 1: ' + t.Column1, '') + 
ISNULL('Column 2: ' + t.Column2, '') + 
ISNULL('Column 3: ' + t.Column3, '') 
FROM Table

在 SQL Server 2012 或更高版本中,可以使用内置函数Concat,但仍需要以旧方式将列连接到其硬编码说明,以利用前面所述的效果。

SELECT CONCAT('Column 1: ' + t.Column1, 
'Column 2: ' + t.Column2, 
'Column 3: ' + t.Column3) 
FROM Table

假设CONCAT_NULL_YIELDS_NULL已打开(默认情况下,应该打开(,您可以执行以下操作:

SELECT COALESCE('Column 1: ' + t.Column1,'') + 
COALESCE('Column 2: ' + t.Column2,'') + 
COALESCE('Column 3: ' + t.Column3,'')
from Table1 t

如果NULL任何列,则将'Column name ' + ColumnNULL。 然后,COALESCENULL替换为空字符串,以便外部+s 连接非 NULL 字符串。

最新更新