AS NewCompoundField - 连接可能为NULL的值

时间:2015-01-19 09:53:55

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

我有以下T-SQL查询;

SELECT      
    Site.Address1 + CHAR(13) + Site.Address2 + CHAR(13) + 
        Site.Address3 + CHAR(13)  + Site.Town + CHAR(13) + 
        Site.eCounty AS SiteAddress
FROM Site

如果构成Site.AddressX的任何SiteAddress字段为NULL,则SiteAddress本身就是NULL。我想要一个Site.AddressX字段,如果它是NULL,则会忽略新行字符。

我尝试为单个字段及其新行字符添加CASE语句,但无法使其生效。

SELECT      
    (CASE WHEN (Site.Address1 IS NULL) THEN '' ELSE Site.Address1 + CHAR(10)) +
        Site.Address2 + CHAR(13) + 
        Site.Address3 + CHAR(13)  + Site.Town + CHAR(13) + 
        Site.eCounty AS SiteAddress
FROM Site

我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT      
        COALESCE([Site].Address1 + CHAR(13), '')  + 
        COALESCE([Site].Address2 + CHAR(13), '')  + 
        COALESCE([Site].Address3 + CHAR(13), '')  + 
        COALESCE([Site].Town + CHAR(13), '') + 
        [Site].eCounty AS SiteAddress
FROM [Site]

答案 1 :(得分:0)

试试这个

SELECT      
    CASE WHEN Site.Address1 IS NULL THEN '' 
    ELSE Site.Address1 + CHAR(10) +
        Site.Address2 + CHAR(13) + 
        Site.Address3 + CHAR(13)  + Site.Town + CHAR(13) + 
        Site.eCounty END AS SiteAddress 
FROM SITE Site