SQL Server条件邮件地址格式

时间:2010-03-17 17:59:34

标签: sql sql-server

我有以下SQL来将美国地址格式化为邮件地址的每一行,但它相当难看。有没有更好的方法来解决这个问题,还是它必须是这个丑陋的?此外,这段代码的问题在于它最终会在最后添加一条额外的新行。

declare @NL varchar(2);
set @NL = char(13) + char(10);

select 
  case when rtrim(coalesce(AttentionLine,'') ) != '' then rtrim(AttentionLine ) + @NL else '' end
  + case when rtrim(coalesce(Recipient,'') ) != '' then rtrim(Recipient ) + @NL else '' end
  + case when rtrim(coalesce(AddlAddrLine,'') ) != '' then rtrim(AddlAddrLine ) + @NL else '' end
  + case when rtrim(coalesce(DeliveryAddr,'') ) != '' then rtrim(DeliveryAddr ) + @NL else '' end
  + case when rtrim(coalesce(LastLine,'') ) != '' then rtrim(LastLine ) + @NL else '' end
  + case when rtrim(coalesce(Country,'') ) != '' then rtrim(Country ) + @NL else '' end
as FormattedMailingAddress    
from Address 
where Id = 1

2 个答案:

答案 0 :(得分:3)

如果您的Sql Server设置为NULL + varchar返回NULL(SET CONCAT_NULL_YIELDS_NULL (Transact-SQL)),这可能有所帮助。

DECLARE @Address TABLE(
        ID INT,
        AttentionLine VARCHAR(50),
        Recipient VARCHAR(50),
        AddlAddrLine VARCHAR(50),
        DeliveryAddr VARCHAR(50),
        LastLine VARCHAR(50),
        Country VARCHAR(50)
)

declare @NL varchar(2); 
set @NL = char(13) + char(10); 

INSERT INTO @Address SELECT 1, NULL, '1', NULL, '2', NULL, '3'

select  
  case when rtrim(coalesce(AttentionLine,'') ) != '' then rtrim(AttentionLine ) + @NL else '' end 
  + case when rtrim(coalesce(Recipient,'') ) != '' then rtrim(Recipient ) + @NL else '' end 
  + case when rtrim(coalesce(AddlAddrLine,'') ) != '' then rtrim(AddlAddrLine ) + @NL else '' end 
  + case when rtrim(coalesce(DeliveryAddr,'') ) != '' then rtrim(DeliveryAddr ) + @NL else '' end 
  + case when rtrim(coalesce(LastLine,'') ) != '' then rtrim(LastLine ) + @NL else '' end 
  + case when rtrim(coalesce(Country,'') ) != '' then rtrim(Country ) + @NL else '' end 
as FormattedMailingAddress     ,
    RTRIM(coalesce(AttentionLine + @NL,'')) + 
    RTRIM(coalesce(Recipient + @NL,'')) + 
    RTRIM(coalesce(AddlAddrLine + @NL,'')) + 
    RTRIM(coalesce(DeliveryAddr + @NL,'')) + 
    RTRIM(coalesce(LastLine + @NL,'')) + 
    RTRIM(coalesce(Country + @NL,'')) 
from @Address  
where Id = 1

答案 1 :(得分:1)

我意识到这是一个老问题,但是这个问题有一个新的解决方案:CONCAT_WS()函数,这是SQL Server 2017的新功能(它也可用于Azure SQL数据库)。

SELECT CONCAT_WS (
    CHAR(13) + CHAR(10),    --Separator
    NULLIF(AttentionLine, ''),
    NULLIF(Recipient, ''),
    NULLIF(AddlAddrLine, ''),
    NULLIF(DeliveryAddr, ''),
    NULLIF(LastLine, ''),
    NULLIF(Country, '')
)
AS FormattedMailingAddress    
FROM Address 
WHERE Id = 1
函数忽略

NULL值,这就是本例中每个参数/参数使用NULLIF的原因。 (当参数/参数求值为NULL时,也不会添加分隔符)。这是一篇简短的博客文章,其中包含更多详细信息:New For SQL Server 2017: T-SQL Function CONCAT_WS