通过Coalesce和NULLIF删除前导逗号?

时间:2013-03-11 15:12:37

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

UPDATE PropertyInformationDump
   SET RegistryAdd = COALESCE(NULLIF(b.OCAREOF, ''), b.OCAREOF + ', ','') +
       COALESCE(NULLIF(b.O1STADD, ''), b.O1STADD + ', ','') + 
       COALESCE(NULLIF(b.O2NDADD, '') + b.O2NDADD + ', ','') + 
       COALESCE(b.OSTNAME + ', ','') + COALESCE(b.OCITYST + '  ','') +  
       COALESCE(NULLIF(b.OZIP, ''), b.OZIP,'')
  FROM dbo.vw_BRT b
 WHERE BRTNumber = b.PARCEL
GO

想要删除这些组合字符串前面的逗号。以下是正在发生的事情的一个例子:

, , 1350 SUSQUEHANNA AVE, PHILADELPHIA PA  19125
MICHAEL J CARLONE, 10050 ROOSEVELT BLVD, PHILADELPHIA PA  191163924

需要它总是看起来像:

1350 SUSQUEHANNA AVE, PHILADELPHIA PA  19125

或者是如何填充OCAREOF的那个:

MICHAEL J CARLONE, 10050 ROOSEVELT BLVD, PHILADELPHIA PA  191163924

如果字段为空或空,我需要删除这些逗号。显然我这样做不正确!

2 个答案:

答案 0 :(得分:1)

使用SQL Server 2005,以下应该可以正常工作

UPDATE PropertyInformationDump
SET RegistryAdd = 
    CASE WHEN Len(b.OCAREOF) > 0 THEN b.OCAREOF + ',' ELSE '' END + 
    CASE WHEN Len(b.O1STADD) > 0 THEN b.O1STADD + ',' ELSE '' END  + 
    CASE WHEN Len(b.O2NDADD) > 0 THEN b.O2NDADD + ',' ELSE '' END  + 
    CASE WHEN Len(b.OSTNAME ) > 0 THEN b.OSTNAME + ',' ELSE '' END  + 
    CASE WHEN Len(b.OCITYST) > 0 THEN b.OCITYST+ ',' ELSE '' END  + 
    CASE WHEN Len(b.OZIP) > 0 THEN b.OZIP+ ',' ELSE '' END 
FROM dbo.vw_BRT b
WHERE BRTNumber = b.PARCEL

如果字段中没有数据,则可以使用isNull()

忽略

答案 1 :(得分:0)

使用此:

COALESCE(NULLIF(b.OCAREOF + ', ', ''),'')

<强>更新

如果您的字段不可为空,请使用以下命令:

CASE WHEN LEN(b.OCAREOF) = 0 THEN '' ELSE b.OCAREOF + ', ' END +
....