SQL IF 语句使用多个 ISNULL

SQL IF Statement using multiple ISNULL

我有下面的代码 returning 访问邮政编码的顺序。我能够正确 return 邮政编码,但为了使数据更加用户友好,我在邮政编码之间添加了破折号 (-)。

问题是因为我不知道如何消除只有 2 或 3 个邮政编码的行的破折号。

SELECT 
    [Qry_Zip Stop Sequence].[Load ID], 
    [1] AS [Stop 1], [2] AS [Stop 2], [3] AS [Stop 3], 
    [4] AS [Stop 4], 
    TMS_Load.[Shipped Date/Time], 
    CONCAT(ISNULL([1], ''), '-', ISNULL([2], ''), '-', ISNULL([3], ''), '-', ISNULL([4], '')) AS [Zip to Zip w Stops]
FROM 
    (SELECT 
         [Load ID], [Sequence], [Stop Zip]
     FROM 
         TMS_Load_Stops) ls
PIVOT 
    (MIN([Stop Zip])
        FOR [Sequence] IN ([1], [2], [3], [4])) AS [Qry_Zip Stop Sequence]
INNER JOIN 
    [TMS_Load] ON [TMS_Load].[Load ID] = [Qry_Zip Stop Sequence].[Load ID]; 

我希望结果只显示有效邮政编码之间的破折号。

78052-45050-45201 or
73350-45220 or
84009-48009-14452 or
36521-38222-87745-95123 or
73368 or
12789-35789

SQL Server 2017 支持CONCAT_WS,专为这种场景设计:

CONCAT_WS ignores null values during concatenation, and does not add the separator between null values. Therefore, CONCAT_WS can cleanly handle concatenation of strings that might have "blank" values - for example, a second address field

SELECT *, CONCAT_WS('-', Stop1, Stop2, Stop3, Stop4) AS r
FROM tab

db<>fiddle demo

以下代码将仅为非 NULL 值插入分隔符。假定列是从左到右填充的。

declare @Stops as Table ( Stop1 Char(5), Stop2 Char(5), Stop3 Char(5), Stop4 Char(5) );
insert into @Stops ( Stop1, Stop2, Stop3, Stop4 ) values
  ( '00001', null, null, null ),
  ( '00001', '00002', null, null ),
  ( '00001', '00002', '00003', null ),
  ( '00001', '00002', '00003', '00004' );


select Coalesce( Stop1, '' ) + Coalesce( '>' + Stop2, '' ) + Coalesce( '>' + Stop3, '' ) +
  Coalesce( '>' + Stop4, '' )
  from @Stops;

旁白:在使用 ZIP+4 代码的地区,破折号以外的分隔符可能不会造成混淆。

使用 stuff().

为每个值添加破折号并删除结果字符串中的第一个破折号——这不一定是第一个值中的那个破折号
stuff(concat('-' + [1],
             '-' + [2],
             '-' + [3],
             '-' + [4]),
      1,
      1,
      '')

注意:我特意混合使用 +concat() 进行字符串连接。 + 在值为 NULL 时产生 NULL,但 concat()NULL 视为空字符串。这样我们就不需要使用很多 coalesce()s 或 isnull()s 等..